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
safeEval.py
#!/usr/bin/env python3 # Copyright 2016 - 2021 Bas van Meerten and Wouter Franssen # This file is part of ssNake. # # ssNake 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. # # ssNake 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 ssNake. If not, see <http://www.gnu.org/licenses/>. import re import numpy as np import scipy.special import hypercomplex as hc def safeEval(inp, length=None, Type='All', x=None): """ Creates a more restricted eval environment. Note that this method is still not acceptable to process strings from untrusted sources. Parameters ---------- inp : str String to evaluate. length : int or float, optional The variable length will be set to this value. By default the variable length is not set. Type : {'All', 'FI', 'C'}, optional Type of expected output. 'All' will return all types, 'FI' will return a float or int, and 'C' will return a complex number. By default Type is set to 'All' x : array_like, optional The variable x is set to this variable, By default the variable x is not used. Returns ------- Object The result of the evaluated string. """ env = vars(np).copy() env.update(vars(hc).copy()) env.update(vars(scipy.special).copy()) env.update(vars(scipy.integrate).copy()) env["locals"] = None env["globals"] = None env["__name__"] = None env["__file__"] = None env["__builtins__"] = {'None': None, 'False': False, 'True':True} # None env["slice"] = slice if length is not None: env["length"] = length if x is not None: env["x"] = x inp = re.sub('([0-9]+)[kK]', '\g<1>*1024', str(inp)) try: val = eval(inp, env) if isinstance(val, str): return None if Type == 'All': return val if Type == 'FI': #single float/int type if isinstance(val, (float, int)) and not np.isnan(val) and not np.isinf(val):
return None if Type == 'C': #single complex number if isinstance(val, (float, int, complex)) and not np.isnan(val) and not np.isinf(val): return val return None except Exception: return None
return val
conditional_block
safeEval.py
#!/usr/bin/env python3 # Copyright 2016 - 2021 Bas van Meerten and Wouter Franssen # This file is part of ssNake. # # ssNake 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. # # ssNake is distributed in the hope that it will be useful,
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ssNake. If not, see <http://www.gnu.org/licenses/>. import re import numpy as np import scipy.special import hypercomplex as hc def safeEval(inp, length=None, Type='All', x=None): """ Creates a more restricted eval environment. Note that this method is still not acceptable to process strings from untrusted sources. Parameters ---------- inp : str String to evaluate. length : int or float, optional The variable length will be set to this value. By default the variable length is not set. Type : {'All', 'FI', 'C'}, optional Type of expected output. 'All' will return all types, 'FI' will return a float or int, and 'C' will return a complex number. By default Type is set to 'All' x : array_like, optional The variable x is set to this variable, By default the variable x is not used. Returns ------- Object The result of the evaluated string. """ env = vars(np).copy() env.update(vars(hc).copy()) env.update(vars(scipy.special).copy()) env.update(vars(scipy.integrate).copy()) env["locals"] = None env["globals"] = None env["__name__"] = None env["__file__"] = None env["__builtins__"] = {'None': None, 'False': False, 'True':True} # None env["slice"] = slice if length is not None: env["length"] = length if x is not None: env["x"] = x inp = re.sub('([0-9]+)[kK]', '\g<1>*1024', str(inp)) try: val = eval(inp, env) if isinstance(val, str): return None if Type == 'All': return val if Type == 'FI': #single float/int type if isinstance(val, (float, int)) and not np.isnan(val) and not np.isinf(val): return val return None if Type == 'C': #single complex number if isinstance(val, (float, int, complex)) and not np.isnan(val) and not np.isinf(val): return val return None except Exception: return None
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
random_line_split
__init__.py
from flask import Flask, jsonify, request from btree import Tree from asteval_wrapper import Script # Startup stuff app = Flask(__name__) app.config.from_object('config') # Jinja initialization to use PyJade app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # Global jinja functions app.jinja_env.globals.update(str=str) app.jinja_env.globals.update(enumerate=enumerate) app.jinja_env.globals.update(len=len) app.jinja_env.globals.update(int=int) app.jinja_env.globals.update(getattr=getattr) app.jinja_env.globals.update(hasattr=hasattr) app.jinja_env.globals.update(isinstance=isinstance) app.jinja_env.globals.update(type=type) app.jinja_env.globals.update(dict=dict) app.jinja_env.globals.update(list=list) app.jinja_env.globals.update(tuple=tuple) app.jinja_env.globals.update(zip=zip) # Import routes from app import single, multiple app.register_blueprint(single.bp) app.register_blueprint(multiple.bp)
def compact(): Tree.from_file().compact() return jsonify(success='compacted') @app.route('/map/', methods=['POST']) def map(): script = Script() tree = Tree.from_file() temp_tree = Tree(filename='map.db') temp_tree.compact() script.add_string(request.get_data()) data = [] for k, v in tree: temp_tree[k] = script.invoke('mapper', k, v) data = script.invoke('reducer', temp_tree.__iter__()) return jsonify(result=data)
@app.route('/compact/', methods=['GET'])
random_line_split
__init__.py
from flask import Flask, jsonify, request from btree import Tree from asteval_wrapper import Script # Startup stuff app = Flask(__name__) app.config.from_object('config') # Jinja initialization to use PyJade app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # Global jinja functions app.jinja_env.globals.update(str=str) app.jinja_env.globals.update(enumerate=enumerate) app.jinja_env.globals.update(len=len) app.jinja_env.globals.update(int=int) app.jinja_env.globals.update(getattr=getattr) app.jinja_env.globals.update(hasattr=hasattr) app.jinja_env.globals.update(isinstance=isinstance) app.jinja_env.globals.update(type=type) app.jinja_env.globals.update(dict=dict) app.jinja_env.globals.update(list=list) app.jinja_env.globals.update(tuple=tuple) app.jinja_env.globals.update(zip=zip) # Import routes from app import single, multiple app.register_blueprint(single.bp) app.register_blueprint(multiple.bp) @app.route('/compact/', methods=['GET']) def compact(): Tree.from_file().compact() return jsonify(success='compacted') @app.route('/map/', methods=['POST']) def
(): script = Script() tree = Tree.from_file() temp_tree = Tree(filename='map.db') temp_tree.compact() script.add_string(request.get_data()) data = [] for k, v in tree: temp_tree[k] = script.invoke('mapper', k, v) data = script.invoke('reducer', temp_tree.__iter__()) return jsonify(result=data)
map
identifier_name
__init__.py
from flask import Flask, jsonify, request from btree import Tree from asteval_wrapper import Script # Startup stuff app = Flask(__name__) app.config.from_object('config') # Jinja initialization to use PyJade app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # Global jinja functions app.jinja_env.globals.update(str=str) app.jinja_env.globals.update(enumerate=enumerate) app.jinja_env.globals.update(len=len) app.jinja_env.globals.update(int=int) app.jinja_env.globals.update(getattr=getattr) app.jinja_env.globals.update(hasattr=hasattr) app.jinja_env.globals.update(isinstance=isinstance) app.jinja_env.globals.update(type=type) app.jinja_env.globals.update(dict=dict) app.jinja_env.globals.update(list=list) app.jinja_env.globals.update(tuple=tuple) app.jinja_env.globals.update(zip=zip) # Import routes from app import single, multiple app.register_blueprint(single.bp) app.register_blueprint(multiple.bp) @app.route('/compact/', methods=['GET']) def compact(): Tree.from_file().compact() return jsonify(success='compacted') @app.route('/map/', methods=['POST']) def map(): script = Script() tree = Tree.from_file() temp_tree = Tree(filename='map.db') temp_tree.compact() script.add_string(request.get_data()) data = [] for k, v in tree:
data = script.invoke('reducer', temp_tree.__iter__()) return jsonify(result=data)
temp_tree[k] = script.invoke('mapper', k, v)
conditional_block
__init__.py
from flask import Flask, jsonify, request from btree import Tree from asteval_wrapper import Script # Startup stuff app = Flask(__name__) app.config.from_object('config') # Jinja initialization to use PyJade app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # Global jinja functions app.jinja_env.globals.update(str=str) app.jinja_env.globals.update(enumerate=enumerate) app.jinja_env.globals.update(len=len) app.jinja_env.globals.update(int=int) app.jinja_env.globals.update(getattr=getattr) app.jinja_env.globals.update(hasattr=hasattr) app.jinja_env.globals.update(isinstance=isinstance) app.jinja_env.globals.update(type=type) app.jinja_env.globals.update(dict=dict) app.jinja_env.globals.update(list=list) app.jinja_env.globals.update(tuple=tuple) app.jinja_env.globals.update(zip=zip) # Import routes from app import single, multiple app.register_blueprint(single.bp) app.register_blueprint(multiple.bp) @app.route('/compact/', methods=['GET']) def compact():
@app.route('/map/', methods=['POST']) def map(): script = Script() tree = Tree.from_file() temp_tree = Tree(filename='map.db') temp_tree.compact() script.add_string(request.get_data()) data = [] for k, v in tree: temp_tree[k] = script.invoke('mapper', k, v) data = script.invoke('reducer', temp_tree.__iter__()) return jsonify(result=data)
Tree.from_file().compact() return jsonify(success='compacted')
identifier_body
plan.py
# -*- coding: utf-8 -*- ### required - do no delete @auth.requires_login() def plan(): return dict() def new(): form = SQLFORM.factory(db.contacts,db.groups) if form.accepts(request.vars): _id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars)) form.vars.contact = _id_user id = db.groups.insert(**db.groups._filter_fields(form.vars)) response.flash = 'User registered successfully' return locals() def
(): id = request.args(0) group = db(db.groups.id == id).select()[0] form = SQLFORM(db.contacts, group.contact.id) group = SQLFORM(db.group, group.id) # Adding the group form form.append(group) if form.accepts(request.vars): # Updating the contacts db.contacts.update(**db.contacts._filter_fields(form.vars)) # Atualizando o grupo old_group = db(db.groups.id == group.id).select().first() old_group.update_record(group=group.vars.group) response.session = 'Updated with success!' return locals()
update
identifier_name
plan.py
# -*- coding: utf-8 -*- ### required - do no delete @auth.requires_login() def plan(): return dict() def new(): form = SQLFORM.factory(db.contacts,db.groups) if form.accepts(request.vars): _id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars)) form.vars.contact = _id_user id = db.groups.insert(**db.groups._filter_fields(form.vars)) response.flash = 'User registered successfully' return locals() def update(): id = request.args(0) group = db(db.groups.id == id).select()[0] form = SQLFORM(db.contacts, group.contact.id) group = SQLFORM(db.group, group.id) # Adding the group form form.append(group) if form.accepts(request.vars): # Updating the contacts
return locals()
db.contacts.update(**db.contacts._filter_fields(form.vars)) # Atualizando o grupo old_group = db(db.groups.id == group.id).select().first() old_group.update_record(group=group.vars.group) response.session = 'Updated with success!'
conditional_block
plan.py
# -*- coding: utf-8 -*- ### required - do no delete @auth.requires_login() def plan(): return dict() def new(): form = SQLFORM.factory(db.contacts,db.groups) if form.accepts(request.vars): _id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars)) form.vars.contact = _id_user id = db.groups.insert(**db.groups._filter_fields(form.vars))
response.flash = 'User registered successfully' return locals() def update(): id = request.args(0) group = db(db.groups.id == id).select()[0] form = SQLFORM(db.contacts, group.contact.id) group = SQLFORM(db.group, group.id) # Adding the group form form.append(group) if form.accepts(request.vars): # Updating the contacts db.contacts.update(**db.contacts._filter_fields(form.vars)) # Atualizando o grupo old_group = db(db.groups.id == group.id).select().first() old_group.update_record(group=group.vars.group) response.session = 'Updated with success!' return locals()
random_line_split
plan.py
# -*- coding: utf-8 -*- ### required - do no delete @auth.requires_login() def plan():
def new(): form = SQLFORM.factory(db.contacts,db.groups) if form.accepts(request.vars): _id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars)) form.vars.contact = _id_user id = db.groups.insert(**db.groups._filter_fields(form.vars)) response.flash = 'User registered successfully' return locals() def update(): id = request.args(0) group = db(db.groups.id == id).select()[0] form = SQLFORM(db.contacts, group.contact.id) group = SQLFORM(db.group, group.id) # Adding the group form form.append(group) if form.accepts(request.vars): # Updating the contacts db.contacts.update(**db.contacts._filter_fields(form.vars)) # Atualizando o grupo old_group = db(db.groups.id == group.id).select().first() old_group.update_record(group=group.vars.group) response.session = 'Updated with success!' return locals()
return dict()
identifier_body
errorScenarios.js
(function () { 'use strict'; describe('error scenarios', function () { var loginPage = require("../login/loginPage.js"); afterEach(function () { browser.clearMockModules();
var mockServerInfo = function () { var serverInfoService = angular.module('opentele.restApiServices.serverInfo', []); serverInfoService.service('serverInfo', function () { return { get: function (onSuccess, onError) { onError(); } }; }); }; beforeEach(function () { browser.addMockModule('opentele.restApiServices.serverInfo', mockServerInfo); }); it('should show message stating that server is unavailable instead of login form', function () { loginPage.get(); expect(loginPage.loginForm.isDisplayed()).toBe(false); expect(loginPage.errorMessage.getText()).toMatch(/not connect to server/); }); }); describe('show error page on exceptions', function () { var mockRestClient = function () { var authenticationService = angular.module('opentele.restApiServices.authentication', []); authenticationService.service('authentication', function () { return { login: function (username, password, onSuccess, onError) { throw new Error('Wrong something'); }, logout: function (onSuccess) { onSuccess(); } }; }); }; beforeEach(function () { browser.addMockModule('opentele.restApiServices.authentication', mockRestClient); }); it('should redirect to error page when exception is left unhandled', function () { loginPage.get(); loginPage.doLogin("nancyann", "abcd1234"); // will throw exception from mock rest client. expect(browser.getLocationAbsUrl()).toMatch(/\/error/); }); }); describe('show error page on server errors', function () { var menuPage = require("../menu/menuPage.js"); it('should redirect to error page when server responds with error status', function () { loginPage.get(); loginPage.doLogin("measurements500", "1234"); menuPage.toMeasurements(); expect(browser.getLocationAbsUrl()).toMatch(/\/error/); }); }); }); }());
browser.refresh(); }); describe('server unavailable', function () {
random_line_split
header-bar.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header-bar', templateUrl: './header-bar.component.html',
isCollapsed: boolean; githubUrl = 'https://github.com/IckleChris/ic-datepicker'; links = [{ label: 'Installation', routerLink: 'installation' }, { label: 'Example', routerLink: 'example' }, { label: 'Options', routerLink: 'options' }, { label: 'Interfaces', routerLink: 'interfaces' }, { label: 'Events', routerLink: 'events' }, { label: 'Theming', routerLink: 'theming' }, { label: 'Input Template', routerLink: 'input-template' }]; ngOnInit() { this.isCollapsed = true; } }
styleUrls: ['./header-bar.component.scss'] }) export class HeaderBarComponent implements OnInit {
random_line_split
header-bar.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header-bar', templateUrl: './header-bar.component.html', styleUrls: ['./header-bar.component.scss'] }) export class HeaderBarComponent implements OnInit { isCollapsed: boolean; githubUrl = 'https://github.com/IckleChris/ic-datepicker'; links = [{ label: 'Installation', routerLink: 'installation' }, { label: 'Example', routerLink: 'example' }, { label: 'Options', routerLink: 'options' }, { label: 'Interfaces', routerLink: 'interfaces' }, { label: 'Events', routerLink: 'events' }, { label: 'Theming', routerLink: 'theming' }, { label: 'Input Template', routerLink: 'input-template' }]; ngOnInit()
}
{ this.isCollapsed = true; }
identifier_body
header-bar.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header-bar', templateUrl: './header-bar.component.html', styleUrls: ['./header-bar.component.scss'] }) export class HeaderBarComponent implements OnInit { isCollapsed: boolean; githubUrl = 'https://github.com/IckleChris/ic-datepicker'; links = [{ label: 'Installation', routerLink: 'installation' }, { label: 'Example', routerLink: 'example' }, { label: 'Options', routerLink: 'options' }, { label: 'Interfaces', routerLink: 'interfaces' }, { label: 'Events', routerLink: 'events' }, { label: 'Theming', routerLink: 'theming' }, { label: 'Input Template', routerLink: 'input-template' }];
() { this.isCollapsed = true; } }
ngOnInit
identifier_name
Trigger.js
/* Trigger.js * * copyright (c) 2010-2022, Christian Mayer and the CometVisu contributers. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /** * Adds a button to the visu with which exactly a defined value for a short, * as well as a defined value for a long key pressure, can be sent to the BUS, * e.g. for recalling and storing scenes or driving roller blinds. (Short = stop, long = drive). * The address for short and long term may vary. * * @author Christian Mayer * @since 2012 */ qx.Class.define('cv.ui.structure.pure.Trigger', { extend: cv.ui.structure.AbstractWidget, include: [ cv.ui.common.Operate, cv.ui.common.HasAnimatedButton, cv.ui.common.BasicUpdate, cv.ui.common.HandleLongpress ], /* ****************************************************** PROPERTIES ****************************************************** */ properties: { sendValue: { check: 'String', init: '0' }, shortValue: { check: 'String', init: '0' } }, /* ****************************************************** MEMBERS ****************************************************** */ members: { // overridden _onDomReady: function() { this.base(arguments); this.defaultUpdate(undefined, this.getSendValue(), this.getDomElement()); },
_getInnerDomString: function () { return '<div class="actor switchUnpressed"><div class="value">-</div></div>'; }, /** * Handle a short tap event and send the value for short pressing the trigger to the backend. * If there is no short threshold set, this send the value for long presses to the backend. */ _action: function() { const value = (this.getShortThreshold() > 0 || this.isShortDefault()) ? this.getShortValue() : this.getSendValue(); this.sendToBackend(value, function(address) { return !!(address.variantInfo & 1); }); }, /** * Handle a long tap event and send the value for long pressing the trigger to the backend. */ _onLongTap: function() { this.sendToBackend(this.getSendValue(), function(address) { return !!(address.variantInfo & 2); }); } } });
// overridden
random_line_split
mono.rs
/* * Monochrome filter */ #pragma version(1) #pragma rs java_package_name(se.embargo.onebit.filter) rs_allocation gIn; rs_allocation gOut; rs_script gScript; const static float3 gMonoMult = {0.299f, 0.587f, 0.114f}; void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {
} void filter() { int64_t t1 = rsUptimeMillis(); rsForEach(gScript, gIn, gOut, 0); int64_t t2 = rsUptimeMillis(); rsDebug("Monochrome filter in (ms)", t2 - t1); }
float4 pixel = rsUnpackColor8888(*v_in); float3 mono = dot(pixel.rgb, gMonoMult); *v_out = rsPackColorTo8888(mono);
random_line_split
Tooltips.py
from muntjac.ui.abstract_component import AbstractComponent from muntjac.demo.sampler.APIResource import APIResource from muntjac.demo.sampler.Feature import Feature, Version class Tooltips(Feature): def getSinceVersion(self): return Version.OLD def getName(self): return 'Tooltips' def getDescription(self): return ('Most components can have a <i>description</i>,' ' which is usually shown as a <i>\"tooltip\"</i>.' ' In the Form component, the description is shown at the' ' top of the form.' ' Descriptions can have HTML formatted (\'rich\') content.<br/>') def getRelatedAPI(self): return [APIResource(AbstractComponent)] def getRelatedFeatures(self): # TODO Auto-generated method stub return None def getRelatedResources(self): # TODO Auto-generated method stub
return None
identifier_body
Tooltips.py
from muntjac.ui.abstract_component import AbstractComponent from muntjac.demo.sampler.APIResource import APIResource from muntjac.demo.sampler.Feature import Feature, Version class Tooltips(Feature): def getSinceVersion(self): return Version.OLD def getName(self): return 'Tooltips'
' which is usually shown as a <i>\"tooltip\"</i>.' ' In the Form component, the description is shown at the' ' top of the form.' ' Descriptions can have HTML formatted (\'rich\') content.<br/>') def getRelatedAPI(self): return [APIResource(AbstractComponent)] def getRelatedFeatures(self): # TODO Auto-generated method stub return None def getRelatedResources(self): # TODO Auto-generated method stub return None
def getDescription(self): return ('Most components can have a <i>description</i>,'
random_line_split
Tooltips.py
from muntjac.ui.abstract_component import AbstractComponent from muntjac.demo.sampler.APIResource import APIResource from muntjac.demo.sampler.Feature import Feature, Version class Tooltips(Feature): def getSinceVersion(self): return Version.OLD def getName(self): return 'Tooltips' def getDescription(self): return ('Most components can have a <i>description</i>,' ' which is usually shown as a <i>\"tooltip\"</i>.' ' In the Form component, the description is shown at the' ' top of the form.' ' Descriptions can have HTML formatted (\'rich\') content.<br/>') def getRelatedAPI(self): return [APIResource(AbstractComponent)] def getRelatedFeatures(self): # TODO Auto-generated method stub return None def
(self): # TODO Auto-generated method stub return None
getRelatedResources
identifier_name
test_api_version_compare.py
from django.test import TestCase from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.restapi.views.footer_views import get_version_compare_data class VersionCompareTests(TestCase): fixtures = ['eric.json', 'test_data.json'] def
(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.1') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], False) def test_latest_version_highest(self): project = Project.objects.get(slug='read-the-docs') data = get_version_compare_data(project) self.assertEqual(data['is_highest'], True) version = project.versions.get(slug=LATEST) data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True) def test_real_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.2') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True)
test_not_highest
identifier_name
test_api_version_compare.py
from django.test import TestCase from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.restapi.views.footer_views import get_version_compare_data class VersionCompareTests(TestCase): fixtures = ['eric.json', 'test_data.json'] def test_not_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.1') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], False) def test_latest_version_highest(self): project = Project.objects.get(slug='read-the-docs') data = get_version_compare_data(project) self.assertEqual(data['is_highest'], True) version = project.versions.get(slug=LATEST) data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True) def test_real_highest(self):
project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.2') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True)
identifier_body
test_api_version_compare.py
from django.test import TestCase from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.restapi.views.footer_views import get_version_compare_data class VersionCompareTests(TestCase): fixtures = ['eric.json', 'test_data.json']
data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], False) def test_latest_version_highest(self): project = Project.objects.get(slug='read-the-docs') data = get_version_compare_data(project) self.assertEqual(data['is_highest'], True) version = project.versions.get(slug=LATEST) data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True) def test_real_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.2') data = get_version_compare_data(project, version) self.assertEqual(data['is_highest'], True)
def test_not_highest(self): project = Project.objects.get(slug='read-the-docs') version = project.versions.get(slug='0.2.1')
random_line_split
OLDgenseq.servicos.js
//(function () { 'use strict'; angular .module('genseq.servicos') .factory('Autenticacao', Autenticacao); //Autenticacao.$inject = ['$cookies', '$http']; //CORRIGIR COOKIES DEPOIS Autenticacao.$inject = ['$http']; //function Autenticacao($cookies,$http) { //CORRIGIR COOKIES DEPOIS function Autenticacao($http) { var Autenticacao = { registro: registro, login: login, setAuthenticatedUser: setAuthenticatedUser, getAuthenticatedUser: getAuthenticatedUser, isAuthenticated: isAuthenticated, unauthenticate: unauthenticate }; return Autenticacao; function registro(email, password, nome){ return $http.post('127.0.0.1:8000/genseq_api/usuarios',{ email: email, password: password, nome: nome }); } // LOGIN DEPOIS DE REGISTRAR? HMMM function login(email, password) { return $http.post('127.0.0.1:8000/genseq_api/login',{ email: email, password: password }).then(loginSuccess, loginError); function loginSuccess(data, status, headers, config) { Autenticacao.setAuthenticatedUser(data.data); window.location = '/novo_usuario'; //CHECK EFFECT } function loginError(data, status, headers, config) { console.error('Login Error! *sad face* '); } } function setAuthenticatedUser(usuario) { $cookies.authenticatedUser = JSON.stringify(usuario); } function getAuthenticatedUser(){ if (!$cookies.authenticatedUser)
return JSON.parse($cookies.authenticatedUser); } function isAuthenticated() { return !!$cookies.authenticatedUser; } function unauthenticate() { delete $cookies.authenticatedUser; } } //})();
{ return; }
conditional_block
OLDgenseq.servicos.js
//(function () { 'use strict'; angular .module('genseq.servicos') .factory('Autenticacao', Autenticacao); //Autenticacao.$inject = ['$cookies', '$http']; //CORRIGIR COOKIES DEPOIS Autenticacao.$inject = ['$http']; //function Autenticacao($cookies,$http) { //CORRIGIR COOKIES DEPOIS function Autenticacao($http) { var Autenticacao = { registro: registro, login: login, setAuthenticatedUser: setAuthenticatedUser, getAuthenticatedUser: getAuthenticatedUser, isAuthenticated: isAuthenticated, unauthenticate: unauthenticate }; return Autenticacao; function registro(email, password, nome){ return $http.post('127.0.0.1:8000/genseq_api/usuarios',{ email: email, password: password, nome: nome }); } // LOGIN DEPOIS DE REGISTRAR? HMMM function login(email, password) { return $http.post('127.0.0.1:8000/genseq_api/login',{ email: email, password: password }).then(loginSuccess, loginError); function loginSuccess(data, status, headers, config) { Autenticacao.setAuthenticatedUser(data.data); window.location = '/novo_usuario'; //CHECK EFFECT } function loginError(data, status, headers, config) { console.error('Login Error! *sad face* '); } } function setAuthenticatedUser(usuario) { $cookies.authenticatedUser = JSON.stringify(usuario); } function getAuthenticatedUser(){ if (!$cookies.authenticatedUser){ return; } return JSON.parse($cookies.authenticatedUser); } function isAuthenticated()
function unauthenticate() { delete $cookies.authenticatedUser; } } //})();
{ return !!$cookies.authenticatedUser; }
identifier_body
OLDgenseq.servicos.js
//(function () { 'use strict'; angular .module('genseq.servicos') .factory('Autenticacao', Autenticacao); //Autenticacao.$inject = ['$cookies', '$http']; //CORRIGIR COOKIES DEPOIS Autenticacao.$inject = ['$http']; //function Autenticacao($cookies,$http) { //CORRIGIR COOKIES DEPOIS function Autenticacao($http) { var Autenticacao = { registro: registro, login: login, setAuthenticatedUser: setAuthenticatedUser, getAuthenticatedUser: getAuthenticatedUser, isAuthenticated: isAuthenticated, unauthenticate: unauthenticate }; return Autenticacao; function registro(email, password, nome){ return $http.post('127.0.0.1:8000/genseq_api/usuarios',{ email: email, password: password, nome: nome }); } // LOGIN DEPOIS DE REGISTRAR? HMMM function login(email, password) { return $http.post('127.0.0.1:8000/genseq_api/login',{ email: email, password: password }).then(loginSuccess, loginError); function loginSuccess(data, status, headers, config) { Autenticacao.setAuthenticatedUser(data.data); window.location = '/novo_usuario'; //CHECK EFFECT } function loginError(data, status, headers, config) { console.error('Login Error! *sad face* '); } } function setAuthenticatedUser(usuario) { $cookies.authenticatedUser = JSON.stringify(usuario); } function getAuthenticatedUser(){ if (!$cookies.authenticatedUser){ return; } return JSON.parse($cookies.authenticatedUser); } function
() { return !!$cookies.authenticatedUser; } function unauthenticate() { delete $cookies.authenticatedUser; } } //})();
isAuthenticated
identifier_name
OLDgenseq.servicos.js
//(function () { 'use strict'; angular .module('genseq.servicos') .factory('Autenticacao', Autenticacao); //Autenticacao.$inject = ['$cookies', '$http']; //CORRIGIR COOKIES DEPOIS Autenticacao.$inject = ['$http']; //function Autenticacao($cookies,$http) { //CORRIGIR COOKIES DEPOIS function Autenticacao($http) { var Autenticacao = { registro: registro, login: login, setAuthenticatedUser: setAuthenticatedUser, getAuthenticatedUser: getAuthenticatedUser, isAuthenticated: isAuthenticated, unauthenticate: unauthenticate }; return Autenticacao; function registro(email, password, nome){ return $http.post('127.0.0.1:8000/genseq_api/usuarios',{ email: email, password: password, nome: nome }); } // LOGIN DEPOIS DE REGISTRAR? HMMM function login(email, password) { return $http.post('127.0.0.1:8000/genseq_api/login',{ email: email, password: password }).then(loginSuccess, loginError); function loginSuccess(data, status, headers, config) { Autenticacao.setAuthenticatedUser(data.data);
window.location = '/novo_usuario'; //CHECK EFFECT } function loginError(data, status, headers, config) { console.error('Login Error! *sad face* '); } } function setAuthenticatedUser(usuario) { $cookies.authenticatedUser = JSON.stringify(usuario); } function getAuthenticatedUser(){ if (!$cookies.authenticatedUser){ return; } return JSON.parse($cookies.authenticatedUser); } function isAuthenticated() { return !!$cookies.authenticatedUser; } function unauthenticate() { delete $cookies.authenticatedUser; } } //})();
random_line_split
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError {
pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_game_data(games: &Vec<Game>) -> Result<Vec<GameData>, GameMappingError> { let mut result: Vec<GameData> = Vec::with_capacity(games.len()); let comment_parser = CommentParser::new(); for (index, game) in games.iter().enumerate() { match map_single_game_data(game, &comment_parser) { Ok(game_data) => result.push(game_data), Err(error) => { return Err(GameMappingError { game_number: (index + 1) as u32, error: error }); } } } Ok(result) } fn map_single_game_data(game: &Game, comment_parser: &CommentParser) -> Result<GameData, GameError> { let score10 = match game.termination { GameTermination::WhiteWins => 10, GameTermination::DrawnGame => 5, GameTermination::BlackWins => 0, GameTermination::Unknown => { return Err(GameError::UnknownGameTermination); } }; let mut move_data_vec : Vec<MoveData> = Vec::with_capacity(game.moves.len()); for (ply, move_) in game.moves.iter().enumerate() { let comment_opt = move_.comment.as_ref(); if comment_opt.is_none() { return Err(GameError::MissingComment { ply: ply as u32 }); } let comment = comment_opt.unwrap(); let result = comment_parser.parse(comment); match result { Ok(move_data) => move_data_vec.push(move_data), Err(()) => { return Err(GameError::BadComment { ply: (ply + 1) as u32 }); } } } Ok(GameData { score10: score10, move_data: move_data_vec }) } struct CommentParser { re: Regex } impl CommentParser { pub fn new() -> CommentParser { let re = Regex::new(r"(?x) ^(?P<sign>(-|\+)?) ((?P<mate>M\d+)|((?P<eval>\d+)(\.(?P<eval_dec>\d{2})))) /\d+\s ((?P<time>\d+)(\.(?P<time_dec>\d{1,3}))?s) ").unwrap(); CommentParser { re: re } } pub fn parse(&self, comment: &str) -> Result<MoveData, ()> { let captures_opt = self.re.captures(comment); if captures_opt.is_none() { return Err(()); } let captures = captures_opt.unwrap(); let eval = CommentParser::get_eval(&captures); let time = CommentParser::get_time(&captures); Ok(MoveData { eval: eval, time: time }) } fn get_eval(captures: &Captures) -> i32 { let mut result = 0; result += match captures.name("mate") { None | Some("") => 0, Some(_) => 10000, }; result += match captures.name("eval") { None | Some("") => 0, Some(value) => 100 * value.parse::<i32>().unwrap(), }; result += match captures.name("eval_dec") { None | Some("") => 0, Some(value) => value.parse::<i32>().unwrap(), }; result *= match captures.name("sign") { None | Some("") | Some("+") => 1, Some("-") => -1, _ => unreachable!(), }; result } fn get_time(captures: &Captures) -> u32 { let mut result = 0; result += match captures.name("time") { Some(value) => 1000 * value.parse::<u32>().unwrap(), _ => unreachable!(), }; result += match captures.name("time_dec") { None | Some("") => 0, Some(value) => 10u32.pow((3 - value.len() as i32) as u32) * value.parse::<u32>().unwrap(), }; result } } #[cfg(test)] mod tests { use super::CommentParser; use MoveData; #[test] fn comment_parsing() { let comment_parser = CommentParser::new(); assert_eq!(comment_parser.parse("-1.91/13 0.031s"), Ok(MoveData{ eval: -191, time: 31 })); assert_eq!(comment_parser.parse("+0.18/15 0.45s"), Ok(MoveData{ eval: 18, time: 450 })); assert_eq!(comment_parser.parse("+M17/21 0.020s"), Ok(MoveData{ eval: 10000, time: 20 })); assert_eq!(comment_parser.parse("-M26/18 0.022s"), Ok(MoveData{ eval: -10000, time: 22 })); } }
pub game_number: u32,
random_line_split
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError { pub game_number: u32, pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_game_data(games: &Vec<Game>) -> Result<Vec<GameData>, GameMappingError> { let mut result: Vec<GameData> = Vec::with_capacity(games.len()); let comment_parser = CommentParser::new(); for (index, game) in games.iter().enumerate() { match map_single_game_data(game, &comment_parser) { Ok(game_data) => result.push(game_data), Err(error) => { return Err(GameMappingError { game_number: (index + 1) as u32, error: error }); } } } Ok(result) } fn map_single_game_data(game: &Game, comment_parser: &CommentParser) -> Result<GameData, GameError> { let score10 = match game.termination { GameTermination::WhiteWins => 10, GameTermination::DrawnGame => 5, GameTermination::BlackWins => 0, GameTermination::Unknown => { return Err(GameError::UnknownGameTermination); } }; let mut move_data_vec : Vec<MoveData> = Vec::with_capacity(game.moves.len()); for (ply, move_) in game.moves.iter().enumerate() { let comment_opt = move_.comment.as_ref(); if comment_opt.is_none() { return Err(GameError::MissingComment { ply: ply as u32 }); } let comment = comment_opt.unwrap(); let result = comment_parser.parse(comment); match result { Ok(move_data) => move_data_vec.push(move_data), Err(()) => { return Err(GameError::BadComment { ply: (ply + 1) as u32 }); } } } Ok(GameData { score10: score10, move_data: move_data_vec }) } struct
{ re: Regex } impl CommentParser { pub fn new() -> CommentParser { let re = Regex::new(r"(?x) ^(?P<sign>(-|\+)?) ((?P<mate>M\d+)|((?P<eval>\d+)(\.(?P<eval_dec>\d{2})))) /\d+\s ((?P<time>\d+)(\.(?P<time_dec>\d{1,3}))?s) ").unwrap(); CommentParser { re: re } } pub fn parse(&self, comment: &str) -> Result<MoveData, ()> { let captures_opt = self.re.captures(comment); if captures_opt.is_none() { return Err(()); } let captures = captures_opt.unwrap(); let eval = CommentParser::get_eval(&captures); let time = CommentParser::get_time(&captures); Ok(MoveData { eval: eval, time: time }) } fn get_eval(captures: &Captures) -> i32 { let mut result = 0; result += match captures.name("mate") { None | Some("") => 0, Some(_) => 10000, }; result += match captures.name("eval") { None | Some("") => 0, Some(value) => 100 * value.parse::<i32>().unwrap(), }; result += match captures.name("eval_dec") { None | Some("") => 0, Some(value) => value.parse::<i32>().unwrap(), }; result *= match captures.name("sign") { None | Some("") | Some("+") => 1, Some("-") => -1, _ => unreachable!(), }; result } fn get_time(captures: &Captures) -> u32 { let mut result = 0; result += match captures.name("time") { Some(value) => 1000 * value.parse::<u32>().unwrap(), _ => unreachable!(), }; result += match captures.name("time_dec") { None | Some("") => 0, Some(value) => 10u32.pow((3 - value.len() as i32) as u32) * value.parse::<u32>().unwrap(), }; result } } #[cfg(test)] mod tests { use super::CommentParser; use MoveData; #[test] fn comment_parsing() { let comment_parser = CommentParser::new(); assert_eq!(comment_parser.parse("-1.91/13 0.031s"), Ok(MoveData{ eval: -191, time: 31 })); assert_eq!(comment_parser.parse("+0.18/15 0.45s"), Ok(MoveData{ eval: 18, time: 450 })); assert_eq!(comment_parser.parse("+M17/21 0.020s"), Ok(MoveData{ eval: 10000, time: 20 })); assert_eq!(comment_parser.parse("-M26/18 0.022s"), Ok(MoveData{ eval: -10000, time: 22 })); } }
CommentParser
identifier_name
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError { pub game_number: u32, pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_game_data(games: &Vec<Game>) -> Result<Vec<GameData>, GameMappingError> { let mut result: Vec<GameData> = Vec::with_capacity(games.len()); let comment_parser = CommentParser::new(); for (index, game) in games.iter().enumerate() { match map_single_game_data(game, &comment_parser) { Ok(game_data) => result.push(game_data), Err(error) => { return Err(GameMappingError { game_number: (index + 1) as u32, error: error }); } } } Ok(result) } fn map_single_game_data(game: &Game, comment_parser: &CommentParser) -> Result<GameData, GameError> { let score10 = match game.termination { GameTermination::WhiteWins => 10, GameTermination::DrawnGame => 5, GameTermination::BlackWins => 0, GameTermination::Unknown => { return Err(GameError::UnknownGameTermination); } }; let mut move_data_vec : Vec<MoveData> = Vec::with_capacity(game.moves.len()); for (ply, move_) in game.moves.iter().enumerate() { let comment_opt = move_.comment.as_ref(); if comment_opt.is_none() { return Err(GameError::MissingComment { ply: ply as u32 }); } let comment = comment_opt.unwrap(); let result = comment_parser.parse(comment); match result { Ok(move_data) => move_data_vec.push(move_data), Err(()) => { return Err(GameError::BadComment { ply: (ply + 1) as u32 }); } } } Ok(GameData { score10: score10, move_data: move_data_vec }) } struct CommentParser { re: Regex } impl CommentParser { pub fn new() -> CommentParser { let re = Regex::new(r"(?x) ^(?P<sign>(-|\+)?) ((?P<mate>M\d+)|((?P<eval>\d+)(\.(?P<eval_dec>\d{2})))) /\d+\s ((?P<time>\d+)(\.(?P<time_dec>\d{1,3}))?s) ").unwrap(); CommentParser { re: re } } pub fn parse(&self, comment: &str) -> Result<MoveData, ()>
fn get_eval(captures: &Captures) -> i32 { let mut result = 0; result += match captures.name("mate") { None | Some("") => 0, Some(_) => 10000, }; result += match captures.name("eval") { None | Some("") => 0, Some(value) => 100 * value.parse::<i32>().unwrap(), }; result += match captures.name("eval_dec") { None | Some("") => 0, Some(value) => value.parse::<i32>().unwrap(), }; result *= match captures.name("sign") { None | Some("") | Some("+") => 1, Some("-") => -1, _ => unreachable!(), }; result } fn get_time(captures: &Captures) -> u32 { let mut result = 0; result += match captures.name("time") { Some(value) => 1000 * value.parse::<u32>().unwrap(), _ => unreachable!(), }; result += match captures.name("time_dec") { None | Some("") => 0, Some(value) => 10u32.pow((3 - value.len() as i32) as u32) * value.parse::<u32>().unwrap(), }; result } } #[cfg(test)] mod tests { use super::CommentParser; use MoveData; #[test] fn comment_parsing() { let comment_parser = CommentParser::new(); assert_eq!(comment_parser.parse("-1.91/13 0.031s"), Ok(MoveData{ eval: -191, time: 31 })); assert_eq!(comment_parser.parse("+0.18/15 0.45s"), Ok(MoveData{ eval: 18, time: 450 })); assert_eq!(comment_parser.parse("+M17/21 0.020s"), Ok(MoveData{ eval: 10000, time: 20 })); assert_eq!(comment_parser.parse("-M26/18 0.022s"), Ok(MoveData{ eval: -10000, time: 22 })); } }
{ let captures_opt = self.re.captures(comment); if captures_opt.is_none() { return Err(()); } let captures = captures_opt.unwrap(); let eval = CommentParser::get_eval(&captures); let time = CommentParser::get_time(&captures); Ok(MoveData { eval: eval, time: time }) }
identifier_body
c_windows.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! C definitions used by libnative that don't belong in liblibc #![allow(type_overflow)] use libc; pub static WSADESCRIPTION_LEN: uint = 256; pub static WSASYS_STATUS_LEN: uint = 128; pub static FIONBIO: libc::c_long = 0x8004667e; static FD_SETSIZE: uint = 64; pub static MSG_DONTWAIT: libc::c_int = 0; pub static ERROR_ILLEGAL_CHARACTER: libc::c_int = 582; pub static ENABLE_ECHO_INPUT: libc::DWORD = 0x4; pub static ENABLE_EXTENDED_FLAGS: libc::DWORD = 0x80; pub static ENABLE_INSERT_MODE: libc::DWORD = 0x20; pub static ENABLE_LINE_INPUT: libc::DWORD = 0x2; pub static ENABLE_PROCESSED_INPUT: libc::DWORD = 0x1; pub static ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; pub static WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; pub static FD_ACCEPT: libc::c_long = 0x08; pub static FD_MAX_EVENTS: uint = 10; pub static WSA_INFINITE: libc::DWORD = libc::INFINITE; pub static WSA_WAIT_TIMEOUT: libc::DWORD = libc::consts::os::extra::WAIT_TIMEOUT; pub static WSA_WAIT_EVENT_0: libc::DWORD = libc::consts::os::extra::WAIT_OBJECT_0; pub static WSA_WAIT_FAILED: libc::DWORD = libc::consts::os::extra::WAIT_FAILED; #[repr(C)] #[cfg(target_arch = "x86")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, } #[repr(C)] #[cfg(target_arch = "x86_64")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], } pub type LPWSADATA = *mut WSADATA; #[repr(C)] pub struct WSANETWORKEVENTS { pub lNetworkEvents: libc::c_long, pub iErrorCode: [libc::c_int, ..FD_MAX_EVENTS], } pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; pub type WSAEVENT = libc::HANDLE; #[repr(C)] pub struct fd_set { fd_count: libc::c_uint, fd_array: [libc::SOCKET, ..FD_SETSIZE], } pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { set.fd_array[set.fd_count as uint] = s; set.fd_count += 1; } #[link(name = "ws2_32")] extern "system" { pub fn WSAStartup(wVersionRequested: libc::WORD, lpWSAData: LPWSADATA) -> libc::c_int; pub fn WSAGetLastError() -> libc::c_int; pub fn WSACloseEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSACreateEvent() -> WSAEVENT; pub fn WSAEventSelect(s: libc::SOCKET, hEventObject: WSAEVENT, lNetworkEvents: libc::c_long) -> libc::c_int; pub fn WSASetEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSAWaitForMultipleEvents(cEvents: libc::DWORD, lphEvents: *const WSAEVENT, fWaitAll: libc::BOOL, dwTimeout: libc::DWORD, fAltertable: libc::BOOL) -> libc::DWORD; pub fn WSAEnumNetworkEvents(s: libc::SOCKET, hEventObject: WSAEVENT, lpNetworkEvents: LPWSANETWORKEVENTS) -> libc::c_int; pub fn ioctlsocket(s: libc::SOCKET, cmd: libc::c_long, argp: *mut libc::c_ulong) -> libc::c_int; pub fn select(nfds: libc::c_int, readfds: *mut fd_set, writefds: *mut fd_set, exceptfds: *mut fd_set, timeout: *mut libc::timeval) -> libc::c_int; pub fn getsockopt(sockfd: libc::SOCKET, level: libc::c_int, optname: libc::c_int, optval: *mut libc::c_char, optlen: *mut libc::c_int) -> libc::c_int; pub fn SetEvent(hEvent: libc::HANDLE) -> libc::BOOL; pub fn WaitForMultipleObjects(nCount: libc::DWORD, lpHandles: *const libc::HANDLE, bWaitAll: libc::BOOL, dwMilliseconds: libc::DWORD) -> libc::DWORD; pub fn CancelIo(hFile: libc::HANDLE) -> libc::BOOL; pub fn CancelIoEx(hFile: libc::HANDLE, lpOverlapped: libc::LPOVERLAPPED) -> libc::BOOL; } pub mod compat { use std::intrinsics::{atomic_store_relaxed, transmute}; use std::iter::Iterator; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; extern "system" { fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> LPVOID; } // store_func() is idempotent, so using relaxed ordering for the atomics // should be enough. This way, calling a function in this compatibility // layer (after it's loaded) shouldn't be any slower than a regular DLL // call. unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) { let module: Vec<u16> = module.utf16_units().collect(); let module = module.append_one(0); symbol.with_c_str(|symbol| { let handle = GetModuleHandleW(module.as_ptr()); let func: uint = transmute(GetProcAddress(handle, symbol)); atomic_store_relaxed(ptr, if func == 0 { fallback } else { func }) }) } /// Macro for creating a compatibility fallback for a Windows function /// /// # Example /// ``` /// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) { /// // Fallback implementation /// }) /// ``` /// /// Note that arguments unused by the fallback implementation should not be called `_` as /// they are used to be passed to the real function if available. macro_rules! compat_fn( ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty $fallback:block) => ( #[inline(always)] pub unsafe fn $symbol($($argname: $argtype),*) -> $rettype { static mut ptr: extern "system" fn($($argname: $argtype),*) -> $rettype = thunk; extern "system" fn thunk($($argname: $argtype),*) -> $rettype { unsafe { ::io::c::compat::store_func(&mut ptr as *mut _ as *mut uint, stringify!($module), stringify!($symbol), fallback as uint); ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } } extern "system" fn fallback($($argname: $argtype),*) -> $rettype $fallback ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } ); ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) $fallback:block) => ( compat_fn!($module::$symbol($($argname: $argtype),*) -> () $fallback) ) ) /// Compatibility layer for functions in `kernel32.dll` /// /// Latest versions of Windows this is needed for: /// /// * `CreateSymbolicLinkW`: Windows XP, Windows Server 2003 /// * `GetFinalPathNameByHandleW`: Windows XP, Windows Server 2003 pub mod kernel32 { use libc::types::os::arch::extra::{DWORD, LPCWSTR, BOOLEAN, HANDLE}; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; extern "system" { fn SetLastError(dwErrCode: DWORD); } compat_fn!(kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR, _lpTargetFileName: LPCWSTR, _dwFlags: DWORD) -> BOOLEAN { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) compat_fn!(kernel32::GetFinalPathNameByHandleW(_hFile: HANDLE, _lpszFilePath: LPCWSTR, _cchFilePath: DWORD, _dwFlags: DWORD) -> DWORD { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) } } extern "system" { // FIXME - pInputControl should be PCONSOLE_READCONSOLE_CONTROL pub fn ReadConsoleW(hConsoleInput: libc::HANDLE, lpBuffer: libc::LPVOID, nNumberOfCharsToRead: libc::DWORD, lpNumberOfCharsRead: libc::LPDWORD, pInputControl: libc::LPVOID) -> libc::BOOL; pub fn WriteConsoleW(hConsoleOutput: libc::HANDLE, lpBuffer: libc::types::os::arch::extra::LPCVOID, nNumberOfCharsToWrite: libc::DWORD, lpNumberOfCharsWritten: libc::LPDWORD, lpReserved: libc::LPVOID) -> libc::BOOL; pub fn GetConsoleMode(hConsoleHandle: libc::HANDLE, lpMode: libc::LPDWORD) -> libc::BOOL;
lpMode: libc::DWORD) -> libc::BOOL; }
pub fn SetConsoleMode(hConsoleHandle: libc::HANDLE,
random_line_split
c_windows.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! C definitions used by libnative that don't belong in liblibc #![allow(type_overflow)] use libc; pub static WSADESCRIPTION_LEN: uint = 256; pub static WSASYS_STATUS_LEN: uint = 128; pub static FIONBIO: libc::c_long = 0x8004667e; static FD_SETSIZE: uint = 64; pub static MSG_DONTWAIT: libc::c_int = 0; pub static ERROR_ILLEGAL_CHARACTER: libc::c_int = 582; pub static ENABLE_ECHO_INPUT: libc::DWORD = 0x4; pub static ENABLE_EXTENDED_FLAGS: libc::DWORD = 0x80; pub static ENABLE_INSERT_MODE: libc::DWORD = 0x20; pub static ENABLE_LINE_INPUT: libc::DWORD = 0x2; pub static ENABLE_PROCESSED_INPUT: libc::DWORD = 0x1; pub static ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; pub static WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; pub static FD_ACCEPT: libc::c_long = 0x08; pub static FD_MAX_EVENTS: uint = 10; pub static WSA_INFINITE: libc::DWORD = libc::INFINITE; pub static WSA_WAIT_TIMEOUT: libc::DWORD = libc::consts::os::extra::WAIT_TIMEOUT; pub static WSA_WAIT_EVENT_0: libc::DWORD = libc::consts::os::extra::WAIT_OBJECT_0; pub static WSA_WAIT_FAILED: libc::DWORD = libc::consts::os::extra::WAIT_FAILED; #[repr(C)] #[cfg(target_arch = "x86")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, } #[repr(C)] #[cfg(target_arch = "x86_64")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], } pub type LPWSADATA = *mut WSADATA; #[repr(C)] pub struct WSANETWORKEVENTS { pub lNetworkEvents: libc::c_long, pub iErrorCode: [libc::c_int, ..FD_MAX_EVENTS], } pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; pub type WSAEVENT = libc::HANDLE; #[repr(C)] pub struct
{ fd_count: libc::c_uint, fd_array: [libc::SOCKET, ..FD_SETSIZE], } pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { set.fd_array[set.fd_count as uint] = s; set.fd_count += 1; } #[link(name = "ws2_32")] extern "system" { pub fn WSAStartup(wVersionRequested: libc::WORD, lpWSAData: LPWSADATA) -> libc::c_int; pub fn WSAGetLastError() -> libc::c_int; pub fn WSACloseEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSACreateEvent() -> WSAEVENT; pub fn WSAEventSelect(s: libc::SOCKET, hEventObject: WSAEVENT, lNetworkEvents: libc::c_long) -> libc::c_int; pub fn WSASetEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSAWaitForMultipleEvents(cEvents: libc::DWORD, lphEvents: *const WSAEVENT, fWaitAll: libc::BOOL, dwTimeout: libc::DWORD, fAltertable: libc::BOOL) -> libc::DWORD; pub fn WSAEnumNetworkEvents(s: libc::SOCKET, hEventObject: WSAEVENT, lpNetworkEvents: LPWSANETWORKEVENTS) -> libc::c_int; pub fn ioctlsocket(s: libc::SOCKET, cmd: libc::c_long, argp: *mut libc::c_ulong) -> libc::c_int; pub fn select(nfds: libc::c_int, readfds: *mut fd_set, writefds: *mut fd_set, exceptfds: *mut fd_set, timeout: *mut libc::timeval) -> libc::c_int; pub fn getsockopt(sockfd: libc::SOCKET, level: libc::c_int, optname: libc::c_int, optval: *mut libc::c_char, optlen: *mut libc::c_int) -> libc::c_int; pub fn SetEvent(hEvent: libc::HANDLE) -> libc::BOOL; pub fn WaitForMultipleObjects(nCount: libc::DWORD, lpHandles: *const libc::HANDLE, bWaitAll: libc::BOOL, dwMilliseconds: libc::DWORD) -> libc::DWORD; pub fn CancelIo(hFile: libc::HANDLE) -> libc::BOOL; pub fn CancelIoEx(hFile: libc::HANDLE, lpOverlapped: libc::LPOVERLAPPED) -> libc::BOOL; } pub mod compat { use std::intrinsics::{atomic_store_relaxed, transmute}; use std::iter::Iterator; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; extern "system" { fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> LPVOID; } // store_func() is idempotent, so using relaxed ordering for the atomics // should be enough. This way, calling a function in this compatibility // layer (after it's loaded) shouldn't be any slower than a regular DLL // call. unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) { let module: Vec<u16> = module.utf16_units().collect(); let module = module.append_one(0); symbol.with_c_str(|symbol| { let handle = GetModuleHandleW(module.as_ptr()); let func: uint = transmute(GetProcAddress(handle, symbol)); atomic_store_relaxed(ptr, if func == 0 { fallback } else { func }) }) } /// Macro for creating a compatibility fallback for a Windows function /// /// # Example /// ``` /// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) { /// // Fallback implementation /// }) /// ``` /// /// Note that arguments unused by the fallback implementation should not be called `_` as /// they are used to be passed to the real function if available. macro_rules! compat_fn( ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty $fallback:block) => ( #[inline(always)] pub unsafe fn $symbol($($argname: $argtype),*) -> $rettype { static mut ptr: extern "system" fn($($argname: $argtype),*) -> $rettype = thunk; extern "system" fn thunk($($argname: $argtype),*) -> $rettype { unsafe { ::io::c::compat::store_func(&mut ptr as *mut _ as *mut uint, stringify!($module), stringify!($symbol), fallback as uint); ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } } extern "system" fn fallback($($argname: $argtype),*) -> $rettype $fallback ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } ); ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) $fallback:block) => ( compat_fn!($module::$symbol($($argname: $argtype),*) -> () $fallback) ) ) /// Compatibility layer for functions in `kernel32.dll` /// /// Latest versions of Windows this is needed for: /// /// * `CreateSymbolicLinkW`: Windows XP, Windows Server 2003 /// * `GetFinalPathNameByHandleW`: Windows XP, Windows Server 2003 pub mod kernel32 { use libc::types::os::arch::extra::{DWORD, LPCWSTR, BOOLEAN, HANDLE}; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; extern "system" { fn SetLastError(dwErrCode: DWORD); } compat_fn!(kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR, _lpTargetFileName: LPCWSTR, _dwFlags: DWORD) -> BOOLEAN { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) compat_fn!(kernel32::GetFinalPathNameByHandleW(_hFile: HANDLE, _lpszFilePath: LPCWSTR, _cchFilePath: DWORD, _dwFlags: DWORD) -> DWORD { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) } } extern "system" { // FIXME - pInputControl should be PCONSOLE_READCONSOLE_CONTROL pub fn ReadConsoleW(hConsoleInput: libc::HANDLE, lpBuffer: libc::LPVOID, nNumberOfCharsToRead: libc::DWORD, lpNumberOfCharsRead: libc::LPDWORD, pInputControl: libc::LPVOID) -> libc::BOOL; pub fn WriteConsoleW(hConsoleOutput: libc::HANDLE, lpBuffer: libc::types::os::arch::extra::LPCVOID, nNumberOfCharsToWrite: libc::DWORD, lpNumberOfCharsWritten: libc::LPDWORD, lpReserved: libc::LPVOID) -> libc::BOOL; pub fn GetConsoleMode(hConsoleHandle: libc::HANDLE, lpMode: libc::LPDWORD) -> libc::BOOL; pub fn SetConsoleMode(hConsoleHandle: libc::HANDLE, lpMode: libc::DWORD) -> libc::BOOL; }
fd_set
identifier_name
c_windows.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! C definitions used by libnative that don't belong in liblibc #![allow(type_overflow)] use libc; pub static WSADESCRIPTION_LEN: uint = 256; pub static WSASYS_STATUS_LEN: uint = 128; pub static FIONBIO: libc::c_long = 0x8004667e; static FD_SETSIZE: uint = 64; pub static MSG_DONTWAIT: libc::c_int = 0; pub static ERROR_ILLEGAL_CHARACTER: libc::c_int = 582; pub static ENABLE_ECHO_INPUT: libc::DWORD = 0x4; pub static ENABLE_EXTENDED_FLAGS: libc::DWORD = 0x80; pub static ENABLE_INSERT_MODE: libc::DWORD = 0x20; pub static ENABLE_LINE_INPUT: libc::DWORD = 0x2; pub static ENABLE_PROCESSED_INPUT: libc::DWORD = 0x1; pub static ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; pub static WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; pub static FD_ACCEPT: libc::c_long = 0x08; pub static FD_MAX_EVENTS: uint = 10; pub static WSA_INFINITE: libc::DWORD = libc::INFINITE; pub static WSA_WAIT_TIMEOUT: libc::DWORD = libc::consts::os::extra::WAIT_TIMEOUT; pub static WSA_WAIT_EVENT_0: libc::DWORD = libc::consts::os::extra::WAIT_OBJECT_0; pub static WSA_WAIT_FAILED: libc::DWORD = libc::consts::os::extra::WAIT_FAILED; #[repr(C)] #[cfg(target_arch = "x86")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, } #[repr(C)] #[cfg(target_arch = "x86_64")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], } pub type LPWSADATA = *mut WSADATA; #[repr(C)] pub struct WSANETWORKEVENTS { pub lNetworkEvents: libc::c_long, pub iErrorCode: [libc::c_int, ..FD_MAX_EVENTS], } pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; pub type WSAEVENT = libc::HANDLE; #[repr(C)] pub struct fd_set { fd_count: libc::c_uint, fd_array: [libc::SOCKET, ..FD_SETSIZE], } pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { set.fd_array[set.fd_count as uint] = s; set.fd_count += 1; } #[link(name = "ws2_32")] extern "system" { pub fn WSAStartup(wVersionRequested: libc::WORD, lpWSAData: LPWSADATA) -> libc::c_int; pub fn WSAGetLastError() -> libc::c_int; pub fn WSACloseEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSACreateEvent() -> WSAEVENT; pub fn WSAEventSelect(s: libc::SOCKET, hEventObject: WSAEVENT, lNetworkEvents: libc::c_long) -> libc::c_int; pub fn WSASetEvent(hEvent: WSAEVENT) -> libc::BOOL; pub fn WSAWaitForMultipleEvents(cEvents: libc::DWORD, lphEvents: *const WSAEVENT, fWaitAll: libc::BOOL, dwTimeout: libc::DWORD, fAltertable: libc::BOOL) -> libc::DWORD; pub fn WSAEnumNetworkEvents(s: libc::SOCKET, hEventObject: WSAEVENT, lpNetworkEvents: LPWSANETWORKEVENTS) -> libc::c_int; pub fn ioctlsocket(s: libc::SOCKET, cmd: libc::c_long, argp: *mut libc::c_ulong) -> libc::c_int; pub fn select(nfds: libc::c_int, readfds: *mut fd_set, writefds: *mut fd_set, exceptfds: *mut fd_set, timeout: *mut libc::timeval) -> libc::c_int; pub fn getsockopt(sockfd: libc::SOCKET, level: libc::c_int, optname: libc::c_int, optval: *mut libc::c_char, optlen: *mut libc::c_int) -> libc::c_int; pub fn SetEvent(hEvent: libc::HANDLE) -> libc::BOOL; pub fn WaitForMultipleObjects(nCount: libc::DWORD, lpHandles: *const libc::HANDLE, bWaitAll: libc::BOOL, dwMilliseconds: libc::DWORD) -> libc::DWORD; pub fn CancelIo(hFile: libc::HANDLE) -> libc::BOOL; pub fn CancelIoEx(hFile: libc::HANDLE, lpOverlapped: libc::LPOVERLAPPED) -> libc::BOOL; } pub mod compat { use std::intrinsics::{atomic_store_relaxed, transmute}; use std::iter::Iterator; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; extern "system" { fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> LPVOID; } // store_func() is idempotent, so using relaxed ordering for the atomics // should be enough. This way, calling a function in this compatibility // layer (after it's loaded) shouldn't be any slower than a regular DLL // call. unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) { let module: Vec<u16> = module.utf16_units().collect(); let module = module.append_one(0); symbol.with_c_str(|symbol| { let handle = GetModuleHandleW(module.as_ptr()); let func: uint = transmute(GetProcAddress(handle, symbol)); atomic_store_relaxed(ptr, if func == 0
else { func }) }) } /// Macro for creating a compatibility fallback for a Windows function /// /// # Example /// ``` /// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) { /// // Fallback implementation /// }) /// ``` /// /// Note that arguments unused by the fallback implementation should not be called `_` as /// they are used to be passed to the real function if available. macro_rules! compat_fn( ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty $fallback:block) => ( #[inline(always)] pub unsafe fn $symbol($($argname: $argtype),*) -> $rettype { static mut ptr: extern "system" fn($($argname: $argtype),*) -> $rettype = thunk; extern "system" fn thunk($($argname: $argtype),*) -> $rettype { unsafe { ::io::c::compat::store_func(&mut ptr as *mut _ as *mut uint, stringify!($module), stringify!($symbol), fallback as uint); ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } } extern "system" fn fallback($($argname: $argtype),*) -> $rettype $fallback ::std::intrinsics::atomic_load_relaxed(&ptr)($($argname),*) } ); ($module:ident::$symbol:ident($($argname:ident: $argtype:ty),*) $fallback:block) => ( compat_fn!($module::$symbol($($argname: $argtype),*) -> () $fallback) ) ) /// Compatibility layer for functions in `kernel32.dll` /// /// Latest versions of Windows this is needed for: /// /// * `CreateSymbolicLinkW`: Windows XP, Windows Server 2003 /// * `GetFinalPathNameByHandleW`: Windows XP, Windows Server 2003 pub mod kernel32 { use libc::types::os::arch::extra::{DWORD, LPCWSTR, BOOLEAN, HANDLE}; use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED; extern "system" { fn SetLastError(dwErrCode: DWORD); } compat_fn!(kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR, _lpTargetFileName: LPCWSTR, _dwFlags: DWORD) -> BOOLEAN { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) compat_fn!(kernel32::GetFinalPathNameByHandleW(_hFile: HANDLE, _lpszFilePath: LPCWSTR, _cchFilePath: DWORD, _dwFlags: DWORD) -> DWORD { unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); } 0 }) } } extern "system" { // FIXME - pInputControl should be PCONSOLE_READCONSOLE_CONTROL pub fn ReadConsoleW(hConsoleInput: libc::HANDLE, lpBuffer: libc::LPVOID, nNumberOfCharsToRead: libc::DWORD, lpNumberOfCharsRead: libc::LPDWORD, pInputControl: libc::LPVOID) -> libc::BOOL; pub fn WriteConsoleW(hConsoleOutput: libc::HANDLE, lpBuffer: libc::types::os::arch::extra::LPCVOID, nNumberOfCharsToWrite: libc::DWORD, lpNumberOfCharsWritten: libc::LPDWORD, lpReserved: libc::LPVOID) -> libc::BOOL; pub fn GetConsoleMode(hConsoleHandle: libc::HANDLE, lpMode: libc::LPDWORD) -> libc::BOOL; pub fn SetConsoleMode(hConsoleHandle: libc::HANDLE, lpMode: libc::DWORD) -> libc::BOOL; }
{ fallback }
conditional_block
TestOutOfRangeDiscretizableColorTransferFunction.py
#!/usr/bin/env python import sys
useBelowRangeColor = 0 if sys.argv.count("--useBelowRangeColor") > 0: useBelowRangeColor = 1 useAboveRangeColor = 0 if sys.argv.count("--useAboveRangeColor") > 0: useAboveRangeColor = 1 cmap = vtk.vtkDiscretizableColorTransferFunction() cmap.AddRGBPoint(-.4, 0.8, 0.8, 0.8) cmap.AddRGBPoint(0.4, 1, 0, 0) cmap.SetUseBelowRangeColor(useBelowRangeColor) cmap.SetBelowRangeColor(0.0, 1.0, 0.0) cmap.SetUseAboveRangeColor(useAboveRangeColor) cmap.SetAboveRangeColor(1.0, 1.0, 0.0) sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(32) sphere.SetThetaResolution(32) sphere.Update() pd = sphere.GetOutput().GetPointData() for i in range(pd.GetNumberOfArrays()): print(pd.GetArray(i).GetName()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphere.GetOutputPort()) mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray("Normals") mapper.ColorByArrayComponent("Normals", 0) mapper.SetLookupTable(cmap) mapper.UseLookupTableScalarRangeOn() mapper.InterpolateScalarsBeforeMappingOn() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.ResetCamera() renderer.ResetCameraClippingRange() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() renWin.Render()
import vtk from vtk.test import Testing
random_line_split
TestOutOfRangeDiscretizableColorTransferFunction.py
#!/usr/bin/env python import sys import vtk from vtk.test import Testing useBelowRangeColor = 0 if sys.argv.count("--useBelowRangeColor") > 0: useBelowRangeColor = 1 useAboveRangeColor = 0 if sys.argv.count("--useAboveRangeColor") > 0:
cmap = vtk.vtkDiscretizableColorTransferFunction() cmap.AddRGBPoint(-.4, 0.8, 0.8, 0.8) cmap.AddRGBPoint(0.4, 1, 0, 0) cmap.SetUseBelowRangeColor(useBelowRangeColor) cmap.SetBelowRangeColor(0.0, 1.0, 0.0) cmap.SetUseAboveRangeColor(useAboveRangeColor) cmap.SetAboveRangeColor(1.0, 1.0, 0.0) sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(32) sphere.SetThetaResolution(32) sphere.Update() pd = sphere.GetOutput().GetPointData() for i in range(pd.GetNumberOfArrays()): print(pd.GetArray(i).GetName()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphere.GetOutputPort()) mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray("Normals") mapper.ColorByArrayComponent("Normals", 0) mapper.SetLookupTable(cmap) mapper.UseLookupTableScalarRangeOn() mapper.InterpolateScalarsBeforeMappingOn() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.ResetCamera() renderer.ResetCameraClippingRange() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() renWin.Render()
useAboveRangeColor = 1
conditional_block
fr.js
/*! * froala_editor v3.2.7 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2021 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * French */ FE.LANGUAGE['fr'] = { translation: { // Place holder 'Type something': 'Tapez quelque chose', // Basic formatting 'Bold': 'Gras', 'Italic': 'Italique', 'Underline': "Soulign\xE9", 'Strikethrough': "Barr\xE9", // Main buttons 'Insert': "Ins\xE9rer", 'Delete': 'Supprimer', 'Cancel': 'Annuler', 'OK': 'Ok', 'Back': 'Retour', 'Remove': 'Supprimer', 'More': 'Plus', 'Update': 'Actualiser', 'Style': 'Style', // Font 'Font Family': "Polices de caract\xE8res", 'Font Size': 'Taille de police', 'Text Color': 'Couleur de police', 'Background Color': 'Couleur d\'arri\xE8re plan', // Colors 'Colors': 'Couleurs', 'Background': "Arri\xE8re-plan", 'Text': 'Texte', 'HEX Color': "Couleur hexad\xE9cimale", // Paragraphs 'Paragraph Format': 'Format de paragraphe', 'Normal': 'Normal', 'Code': 'Code', 'Heading 1': 'Titre 1', 'Heading 2': 'Titre 2', 'Heading 3': 'Titre 3', 'Heading 4': 'Titre 4', 'Line Height': 'Interligne', 'Single': 'Célibataire', // Style 'Paragraph Style': 'Style de paragraphe', 'Inline Style': 'Style en ligne', 'Gray': 'Grise', 'Bordered': 'Bordé', 'Spaced': 'Espacé', 'Uppercase': 'Majuscule', // Alignment 'Align': 'Aligner', 'Align Left': "Aligner \xE0 gauche", 'Align Center': 'Aligner au centre', 'Align Right': "Aligner \xE0 droite", 'Align Justify': 'Justifier', 'None': 'Aucun', // Download PDF 'Download PDF': 'Télécharger le PDF', // Inline Class 'Inline Class': 'Classe en ligne', // Lists 'Ordered List': "Liste ordonn\xE9e", 'Unordered List': "Liste non ordonn\xE9e", 'Default': 'D\xE9faut', 'Circle': 'Cercle', 'Disc': 'Rond', 'Square': 'Carr\xE9', 'Lower Alpha': 'Alpha inf\xE9rieur', 'Lower Greek': 'Grec inf\xE9rieur', 'Lower Roman': 'Romain inf\xE9rieur', 'Upper Alpha': 'Alpha sup\xE9rieur', 'Upper Roman': 'Romain sup\xE9rieur', // Indent 'Decrease Indent': 'Diminuer le retrait', 'Increase Indent': 'Augmenter le retrait', // Links 'Insert Link': "Ins\xE9rer un lien", 'Open in new tab': 'Ouvrir dans un nouvel onglet', 'Open Link': 'Ouvrir le lien', 'Edit Link': 'Modifier le lien', 'Unlink': 'Enlever le lien', 'Choose Link': 'Choisir le lien', // Images 'Insert Image': "Ins\xE9rer une image", 'Upload Image': "T\xE9l\xE9verser une image", 'By URL': 'Par URL', 'Browse': 'Parcourir', 'Drop image': 'Cliquer pour parcourir', 'or click': 'ou glisser/d\xE9poser en plein \xE9cran', 'Manage Images': "G\xE9rer les images", 'Loading': 'Chargement', 'Deleting': 'Suppression', 'Tags': "\xC9tiquettes", 'Are you sure? Image will be deleted.': "Etes-vous certain? L'image sera supprim\xE9e.", 'Replace': 'Remplacer', 'Uploading': 'Envoi en cours', 'Loading image': 'Chargement d\'image en cours', 'Display': 'Afficher', 'Inline': 'En ligne', 'Break Text': 'Rompre le texte', 'Alternative Text': 'Texte alternatif', 'Change Size': 'Changer la dimension', 'Width': 'Largeur', 'Height': 'Hauteur', 'Something went wrong. Please try again.': "Quelque chose a mal tourn\xE9. Veuillez r\xE9essayer.", 'Image Caption': "L\xE9gende de l'image", 'Advanced Edit': "\xC9dition avanc\xE9e", // Video 'Insert Video': "Ins\xE9rer une vid\xE9o", 'Embedded Code': "Code int\xE9gr\xE9", 'Paste in a video URL': "Coller l'URL d'une vid\xE9o", 'Drop video': 'Cliquer pour parcourir', 'Your browser does not support HTML5 video.': "Votre navigateur ne supporte pas les vid\xE9os au format HTML5.", 'Upload Video': "T\xE9l\xE9verser une vid\xE9o", // Tables 'Insert Table': "Ins\xE9rer un tableau", 'Table Header': "Ent\xEAte de tableau", 'Remove Table': 'Supprimer le tableau', 'Table Style': 'Style de tableau', 'Horizontal Align': 'Alignement horizontal', 'Row': 'Ligne', 'Insert row above': "Ins\xE9rer une ligne au-dessus", 'Insert row below': "Ins\xE9rer une ligne en-dessous", 'Delete row': 'Supprimer la ligne', 'Column': 'Colonne', 'Insert column before': "Ins\xE9rer une colonne avant", 'Insert column after': "Ins\xE9rer une colonne apr\xE8s", 'Delete column': 'Supprimer la colonne', 'Cell': 'Cellule', 'Merge cells': 'Fusionner les cellules', 'Horizontal split': 'Diviser horizontalement', 'Vertical split': 'Diviser verticalement', 'Cell Background': "Arri\xE8re-plan de la cellule", 'Vertical Align': 'Alignement vertical', 'Top': 'En haut', 'Middle': 'Au centre', 'Bottom': 'En bas', 'Align Top': 'Aligner en haut', 'Align Middle': 'Aligner au centre', 'Align Bottom': 'Aligner en bas', 'Cell Style': 'Style de cellule', // Files 'Upload File': "T\xE9l\xE9verser un fichier", 'Drop file': 'Cliquer pour parcourir', // Emoticons 'Emoticons': "\xC9motic\xF4nes", 'Grinning face': 'Souriant visage', 'Grinning face with smiling eyes': 'Souriant visage aux yeux souriants', 'Face with tears of joy': "Visage \xE0 des larmes de joie", 'Smiling face with open mouth': 'Visage souriant avec la bouche ouverte', 'Smiling face with open mouth and smiling eyes': 'Visage souriant avec la bouche ouverte et les yeux en souriant', 'Smiling face with open mouth and cold sweat': 'Visage souriant avec la bouche ouverte et la sueur froide', 'Smiling face with open mouth and tightly-closed eyes': "Visage souriant avec la bouche ouverte et les yeux herm\xE9tiquement clos", 'Smiling face with halo': 'Sourire visage avec halo', 'Smiling face with horns': 'Visage souriant avec des cornes',
'Smiling face with heart-shaped eyes': 'Visage souriant avec des yeux en forme de coeur', 'Smiling face with sunglasses': 'Sourire visage avec des lunettes de soleil', 'Smirking face': 'Souriant visage', 'Neutral face': 'Visage neutre', 'Expressionless face': 'Visage sans expression', 'Unamused face': "Visage pas amus\xE9", 'Face with cold sweat': "Face \xE0 la sueur froide", 'Pensive face': 'pensif visage', 'Confused face': 'Visage confus', 'Confounded face': 'visage maudit', 'Kissing face': 'Embrasser le visage', 'Face throwing a kiss': 'Visage jetant un baiser', 'Kissing face with smiling eyes': 'Embrasser le visage avec les yeux souriants', 'Kissing face with closed eyes': "Embrasser le visage avec les yeux ferm\xE9s", 'Face with stuck out tongue': 'Visage avec sortait de la langue', 'Face with stuck out tongue and winking eye': 'Visage avec sortait de la langue et des yeux clignotante', 'Face with stuck out tongue and tightly-closed eyes': "Visage avec sortait de la langue et les yeux ferm\xE9s herm\xE9tiquement", 'Disappointed face': "Visage d\xE9\xE7u", 'Worried face': 'Visage inquiet', 'Angry face': "Visage en col\xE9re", 'Pouting face': 'Faire la moue face', 'Crying face': 'Pleurer visage', 'Persevering face': "Pers\xE9v\xE9rer face", 'Face with look of triumph': 'Visage avec le regard de triomphe', 'Disappointed but relieved face': "D\xE9\xE7u, mais le visage soulag\xE9", 'Frowning face with open mouth': "Les sourcils fronc\xE9s visage avec la bouche ouverte", 'Anguished face': "Visage angoiss\xE9", 'Fearful face': 'Craignant visage', 'Weary face': 'Visage las', 'Sleepy face': 'Visage endormi', 'Tired face': "Visage fatigu\xE9", 'Grimacing face': "Visage grima\xE7ante", 'Loudly crying face': 'Pleurer bruyamment visage', 'Face with open mouth': "Visage \xE0 la bouche ouverte", 'Hushed face': "Visage feutr\xE9e", 'Face with open mouth and cold sweat': "Visage \xE0 la bouche ouverte et la sueur froide", 'Face screaming in fear': 'Visage hurlant de peur', 'Astonished face': "Visage \xE9tonn\xE9", 'Flushed face': "Visage congestionn\xE9", 'Sleeping face': 'Visage au bois dormant', 'Dizzy face': 'Visage vertige', 'Face without mouth': 'Visage sans bouche', 'Face with medical mask': "Visage avec un masque m\xE9dical", // Line breaker 'Break': 'Rompre', // Math 'Subscript': 'Indice', 'Superscript': 'Exposant', // Full screen 'Fullscreen': "Plein \xE9cran", // Horizontal line 'Insert Horizontal Line': "Ins\xE9rer une ligne horizontale", // Clear formatting 'Clear Formatting': 'Effacer le formatage', // Save 'Save': 'Sauvegarder', // Undo, redo 'Undo': 'Annuler', 'Redo': "R\xE9tablir", // Select all 'Select All': "Tout s\xE9lectionner", // Code view 'Code View': 'Mode HTML', // Quote 'Quote': 'Citation', 'Increase': 'Augmenter', 'Decrease': 'Diminuer', // Quick Insert 'Quick Insert': 'Insertion rapide', // Spcial Characters 'Special Characters': "Caract\xE8res sp\xE9ciaux", 'Latin': 'Latin', 'Greek': 'Grec', 'Cyrillic': 'Cyrillique', 'Punctuation': 'Ponctuation', 'Currency': 'Devise', 'Arrows': "Fl\xE8ches", 'Math': 'Math', 'Misc': 'Divers', // Print. 'Print': 'Imprimer', // Spell Checker. 'Spell Checker': 'Correcteur orthographique', // Help 'Help': 'Aide', 'Shortcuts': 'Raccourcis', 'Inline Editor': "\xC9diteur en ligne", 'Show the editor': "Montrer l'\xE9diteur", 'Common actions': 'Actions communes', 'Copy': 'Copier', 'Cut': 'Couper', 'Paste': 'Coller', 'Basic Formatting': 'Formatage de base', 'Increase quote level': 'Augmenter le niveau de citation', 'Decrease quote level': 'Diminuer le niveau de citation', 'Image / Video': "Image / vid\xE9o", 'Resize larger': 'Redimensionner plus grand', 'Resize smaller': 'Redimensionner plus petit', 'Table': 'Table', 'Select table cell': "S\xE9lectionner la cellule du tableau", 'Extend selection one cell': "\xC9tendre la s\xE9lection d'une cellule", 'Extend selection one row': "\xC9tendre la s\xE9lection d'une ligne", 'Navigation': 'Navigation', 'Focus popup / toolbar': 'Focus popup / toolbar', 'Return focus to previous position': "Retourner l'accent sur le poste pr\xE9c\xE9dent", // Embed.ly 'Embed URL': "URL int\xE9gr\xE9e", 'Paste in a URL to embed': "Coller une URL int\xE9gr\xE9e", // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': "Le contenu coll\xE9 provient d'un document Microsoft Word. Voulez-vous conserver le format ou le nettoyer?", 'Keep': 'Conserver', 'Clean': 'Nettoyer', 'Word Paste Detected': "Copiage de mots d\xE9tect\xE9", // Character Counter 'Characters': 'Caract\xE8res', // More Buttons 'More Text': 'Autres options de texte', 'More Paragraph': 'Autres options de paragraphe', 'More Rich': 'Autres options d\'enrichissement', 'More Misc': 'Autres fonctionnalit\xE9s diverses' }, direction: 'ltr' }; }))); //# sourceMappingURL=fr.js.map
'Winking face': 'Clin d\'oeil visage', 'Smiling face with smiling eyes': 'Sourire visage aux yeux souriants', 'Face savoring delicious food': "Visage savourant de d\xE9licieux plats", 'Relieved face': "Soulag\xE9 visage",
random_line_split
polySum.py
''' Week-2:Exercise-grader-polysum A regular polygon has n number of sides. Each side has length s. The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n) The perimeter of a polygon is: length of the boundary of the polygon
''' Input: n - number of sides(should be an integer) s- length of each sides(can be an intger or a float) Output: Returns Sum of area and the square of the perimeter of the regular polygon(gives a float) ''' #Code def areaOfPolygon(n,s): #Pi = 3.1428 area = (0.25 * n * s ** 2)/math.tan(math.pi/n) return area def perimeterOfPolygon(n,s): perimeter = n * s return perimeter sum = areaOfPolygon(n,s) + (perimeterOfPolygon(n,s) ** 2) return round(sum,4)
Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places. ''' #code import math def polysum(n,s):
random_line_split
polySum.py
''' Week-2:Exercise-grader-polysum A regular polygon has n number of sides. Each side has length s. The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n) The perimeter of a polygon is: length of the boundary of the polygon Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places. ''' #code import math def polys
: ''' Input: n - number of sides(should be an integer) s- length of each sides(can be an intger or a float) Output: Returns Sum of area and the square of the perimeter of the regular polygon(gives a float) ''' #Code def areaOfPolygon(n,s): #Pi = 3.1428 area = (0.25 * n * s ** 2)/math.tan(math.pi/n) return area def perimeterOfPolygon(n,s): perimeter = n * s return perimeter sum = areaOfPolygon(n,s) + (perimeterOfPolygon(n,s) ** 2) return round(sum,4)
um(n,s)
identifier_name
polySum.py
''' Week-2:Exercise-grader-polysum A regular polygon has n number of sides. Each side has length s. The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n) The perimeter of a polygon is: length of the boundary of the polygon Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places. ''' #code import math def polysum(n,s): ''' Input: n - number of sides(should be an integer) s- length of each sides(can be an intger or a float) Output: Returns Sum of area and the square of the perimeter of the regular polygon(gives a float) ''' #Code def areaOfPolygon(n,s): #Pi = 3.1428 area = (0.25 * n * s ** 2)/math.tan(math.pi/n) return area def perimeterOfPolygon(n,s): perim
sum = areaOfPolygon(n,s) + (perimeterOfPolygon(n,s) ** 2) return round(sum,4)
eter = n * s return perimeter
identifier_body
rowNodeBlockLoader.ts
import { RowNodeBlock } from "./rowNodeBlock"; import { Bean, PostConstruct, Qualifier } from "../context/context"; import { BeanStub } from "../context/beanStub"; import { Logger, LoggerFactory } from "../logger"; import { _ } from "../utils"; @Bean('rowNodeBlockLoader') export class RowNodeBlockLoader extends BeanStub { public static BLOCK_LOADER_FINISHED_EVENT = 'blockLoaderFinished'; private maxConcurrentRequests: number | undefined; private checkBlockToLoadDebounce: () => void; private activeBlockLoadsCount = 0; private blocks: RowNodeBlock[] = []; private logger: Logger; private active = true; @PostConstruct private postConstruct(): void { this.maxConcurrentRequests = this.gridOptionsWrapper.getMaxConcurrentDatasourceRequests(); const blockLoadDebounceMillis = this.gridOptionsWrapper.getBlockLoadDebounceMillis(); if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) { this.checkBlockToLoadDebounce = _.debounce(this.performCheckBlocksToLoad.bind(this), blockLoadDebounceMillis); } } private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('RowNodeBlockLoader'); } public addBlock(block: RowNodeBlock): void { this.blocks.push(block); // note that we do not remove this listener when removing the block. this is because the // cache can get destroyed (and containing blocks) when a block is loading. however the loading block // is still counted as an active loading block and we must decrement activeBlockLoadsCount when it finishes. block.addEventListener(RowNodeBlock.EVENT_LOAD_COMPLETE, this.loadComplete.bind(this)); this.checkBlockToLoad(); } public removeBlock(block: RowNodeBlock): void { _.removeFromArray(this.blocks, block); } protected destroy(): void { super.destroy(); this.active = false; } private loadComplete(): void { this.activeBlockLoadsCount--; this.checkBlockToLoad();
} public checkBlockToLoad(): void { if (this.checkBlockToLoadDebounce) { this.checkBlockToLoadDebounce(); } else { this.performCheckBlocksToLoad(); } } private performCheckBlocksToLoad(): void { if (!this.active) { return; } this.printCacheStatus(); if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) { this.logger.log(`checkBlockToLoad: max loads exceeded`); return; } let blockToLoad: RowNodeBlock | null = null; this.blocks.forEach(block => { if (block.getState() === RowNodeBlock.STATE_WAITING_TO_LOAD) { blockToLoad = block; } }); if (blockToLoad) { blockToLoad!.load(); this.activeBlockLoadsCount++; this.printCacheStatus(); } } public getBlockState(): any { const result: any = {}; this.blocks.forEach((block: RowNodeBlock) => { const {id, state} = block.getBlockStateJson(); result[id] = state; }); return result; } private printCacheStatus(): void { if (this.logger.isLogging()) { this.logger.log(`printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount},` + ` blocks = ${JSON.stringify(this.getBlockState())}`); } } public isLoading(): boolean { return this.activeBlockLoadsCount > 0; } }
if (this.activeBlockLoadsCount == 0) { this.dispatchEvent({type: RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT}); }
random_line_split
rowNodeBlockLoader.ts
import { RowNodeBlock } from "./rowNodeBlock"; import { Bean, PostConstruct, Qualifier } from "../context/context"; import { BeanStub } from "../context/beanStub"; import { Logger, LoggerFactory } from "../logger"; import { _ } from "../utils"; @Bean('rowNodeBlockLoader') export class RowNodeBlockLoader extends BeanStub { public static BLOCK_LOADER_FINISHED_EVENT = 'blockLoaderFinished'; private maxConcurrentRequests: number | undefined; private checkBlockToLoadDebounce: () => void; private activeBlockLoadsCount = 0; private blocks: RowNodeBlock[] = []; private logger: Logger; private active = true; @PostConstruct private postConstruct(): void { this.maxConcurrentRequests = this.gridOptionsWrapper.getMaxConcurrentDatasourceRequests(); const blockLoadDebounceMillis = this.gridOptionsWrapper.getBlockLoadDebounceMillis(); if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) { this.checkBlockToLoadDebounce = _.debounce(this.performCheckBlocksToLoad.bind(this), blockLoadDebounceMillis); } } private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('RowNodeBlockLoader'); } public addBlock(block: RowNodeBlock): void { this.blocks.push(block); // note that we do not remove this listener when removing the block. this is because the // cache can get destroyed (and containing blocks) when a block is loading. however the loading block // is still counted as an active loading block and we must decrement activeBlockLoadsCount when it finishes. block.addEventListener(RowNodeBlock.EVENT_LOAD_COMPLETE, this.loadComplete.bind(this)); this.checkBlockToLoad(); } public removeBlock(block: RowNodeBlock): void { _.removeFromArray(this.blocks, block); } protected destroy(): void { super.destroy(); this.active = false; } private loadComplete(): void { this.activeBlockLoadsCount--; this.checkBlockToLoad(); if (this.activeBlockLoadsCount == 0) { this.dispatchEvent({type: RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT}); } } public checkBlockToLoad(): void { if (this.checkBlockToLoadDebounce) { this.checkBlockToLoadDebounce(); } else
} private performCheckBlocksToLoad(): void { if (!this.active) { return; } this.printCacheStatus(); if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) { this.logger.log(`checkBlockToLoad: max loads exceeded`); return; } let blockToLoad: RowNodeBlock | null = null; this.blocks.forEach(block => { if (block.getState() === RowNodeBlock.STATE_WAITING_TO_LOAD) { blockToLoad = block; } }); if (blockToLoad) { blockToLoad!.load(); this.activeBlockLoadsCount++; this.printCacheStatus(); } } public getBlockState(): any { const result: any = {}; this.blocks.forEach((block: RowNodeBlock) => { const {id, state} = block.getBlockStateJson(); result[id] = state; }); return result; } private printCacheStatus(): void { if (this.logger.isLogging()) { this.logger.log(`printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount},` + ` blocks = ${JSON.stringify(this.getBlockState())}`); } } public isLoading(): boolean { return this.activeBlockLoadsCount > 0; } }
{ this.performCheckBlocksToLoad(); }
conditional_block
rowNodeBlockLoader.ts
import { RowNodeBlock } from "./rowNodeBlock"; import { Bean, PostConstruct, Qualifier } from "../context/context"; import { BeanStub } from "../context/beanStub"; import { Logger, LoggerFactory } from "../logger"; import { _ } from "../utils"; @Bean('rowNodeBlockLoader') export class RowNodeBlockLoader extends BeanStub { public static BLOCK_LOADER_FINISHED_EVENT = 'blockLoaderFinished'; private maxConcurrentRequests: number | undefined; private checkBlockToLoadDebounce: () => void; private activeBlockLoadsCount = 0; private blocks: RowNodeBlock[] = []; private logger: Logger; private active = true; @PostConstruct private postConstruct(): void { this.maxConcurrentRequests = this.gridOptionsWrapper.getMaxConcurrentDatasourceRequests(); const blockLoadDebounceMillis = this.gridOptionsWrapper.getBlockLoadDebounceMillis(); if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) { this.checkBlockToLoadDebounce = _.debounce(this.performCheckBlocksToLoad.bind(this), blockLoadDebounceMillis); } } private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('RowNodeBlockLoader'); } public addBlock(block: RowNodeBlock): void { this.blocks.push(block); // note that we do not remove this listener when removing the block. this is because the // cache can get destroyed (and containing blocks) when a block is loading. however the loading block // is still counted as an active loading block and we must decrement activeBlockLoadsCount when it finishes. block.addEventListener(RowNodeBlock.EVENT_LOAD_COMPLETE, this.loadComplete.bind(this)); this.checkBlockToLoad(); } public removeBlock(block: RowNodeBlock): void { _.removeFromArray(this.blocks, block); } protected destroy(): void { super.destroy(); this.active = false; } private loadComplete(): void { this.activeBlockLoadsCount--; this.checkBlockToLoad(); if (this.activeBlockLoadsCount == 0) { this.dispatchEvent({type: RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT}); } } public checkBlockToLoad(): void { if (this.checkBlockToLoadDebounce) { this.checkBlockToLoadDebounce(); } else { this.performCheckBlocksToLoad(); } } private performCheckBlocksToLoad(): void
public getBlockState(): any { const result: any = {}; this.blocks.forEach((block: RowNodeBlock) => { const {id, state} = block.getBlockStateJson(); result[id] = state; }); return result; } private printCacheStatus(): void { if (this.logger.isLogging()) { this.logger.log(`printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount},` + ` blocks = ${JSON.stringify(this.getBlockState())}`); } } public isLoading(): boolean { return this.activeBlockLoadsCount > 0; } }
{ if (!this.active) { return; } this.printCacheStatus(); if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) { this.logger.log(`checkBlockToLoad: max loads exceeded`); return; } let blockToLoad: RowNodeBlock | null = null; this.blocks.forEach(block => { if (block.getState() === RowNodeBlock.STATE_WAITING_TO_LOAD) { blockToLoad = block; } }); if (blockToLoad) { blockToLoad!.load(); this.activeBlockLoadsCount++; this.printCacheStatus(); } }
identifier_body
rowNodeBlockLoader.ts
import { RowNodeBlock } from "./rowNodeBlock"; import { Bean, PostConstruct, Qualifier } from "../context/context"; import { BeanStub } from "../context/beanStub"; import { Logger, LoggerFactory } from "../logger"; import { _ } from "../utils"; @Bean('rowNodeBlockLoader') export class RowNodeBlockLoader extends BeanStub { public static BLOCK_LOADER_FINISHED_EVENT = 'blockLoaderFinished'; private maxConcurrentRequests: number | undefined; private checkBlockToLoadDebounce: () => void; private activeBlockLoadsCount = 0; private blocks: RowNodeBlock[] = []; private logger: Logger; private active = true; @PostConstruct private postConstruct(): void { this.maxConcurrentRequests = this.gridOptionsWrapper.getMaxConcurrentDatasourceRequests(); const blockLoadDebounceMillis = this.gridOptionsWrapper.getBlockLoadDebounceMillis(); if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) { this.checkBlockToLoadDebounce = _.debounce(this.performCheckBlocksToLoad.bind(this), blockLoadDebounceMillis); } } private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('RowNodeBlockLoader'); } public addBlock(block: RowNodeBlock): void { this.blocks.push(block); // note that we do not remove this listener when removing the block. this is because the // cache can get destroyed (and containing blocks) when a block is loading. however the loading block // is still counted as an active loading block and we must decrement activeBlockLoadsCount when it finishes. block.addEventListener(RowNodeBlock.EVENT_LOAD_COMPLETE, this.loadComplete.bind(this)); this.checkBlockToLoad(); } public removeBlock(block: RowNodeBlock): void { _.removeFromArray(this.blocks, block); } protected destroy(): void { super.destroy(); this.active = false; } private loadComplete(): void { this.activeBlockLoadsCount--; this.checkBlockToLoad(); if (this.activeBlockLoadsCount == 0) { this.dispatchEvent({type: RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT}); } } public checkBlockToLoad(): void { if (this.checkBlockToLoadDebounce) { this.checkBlockToLoadDebounce(); } else { this.performCheckBlocksToLoad(); } } private
(): void { if (!this.active) { return; } this.printCacheStatus(); if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) { this.logger.log(`checkBlockToLoad: max loads exceeded`); return; } let blockToLoad: RowNodeBlock | null = null; this.blocks.forEach(block => { if (block.getState() === RowNodeBlock.STATE_WAITING_TO_LOAD) { blockToLoad = block; } }); if (blockToLoad) { blockToLoad!.load(); this.activeBlockLoadsCount++; this.printCacheStatus(); } } public getBlockState(): any { const result: any = {}; this.blocks.forEach((block: RowNodeBlock) => { const {id, state} = block.getBlockStateJson(); result[id] = state; }); return result; } private printCacheStatus(): void { if (this.logger.isLogging()) { this.logger.log(`printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount},` + ` blocks = ${JSON.stringify(this.getBlockState())}`); } } public isLoading(): boolean { return this.activeBlockLoadsCount > 0; } }
performCheckBlocksToLoad
identifier_name
yaml.py
# (c) 2017, Brian Coca # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ''' DOCUMENTATION: cache: yaml short_description: File backed, YAML formated. description: - File backed cache that uses YAML as a format, the files are per host. version_added: "2.3" author: Brian Coca (@bcoca) ''' # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import codecs import yaml from ansible.parsing.yaml.loader import AnsibleLoader from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.cache import BaseFileCacheModule class CacheModule(BaseFileCacheModule): """ A caching module backed by yaml files. """ def _load(self, filepath): with codecs.open(filepath, 'r', encoding='utf-8') as f: return AnsibleLoader(f).get_single_data() def _dump(self, value, filepath): with codecs.open(filepath, 'w', encoding='utf-8') as f: yaml.dump(value, f, Dumper=AnsibleDumper, default_flow_style=False)
random_line_split
yaml.py
# (c) 2017, Brian Coca # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ''' DOCUMENTATION: cache: yaml short_description: File backed, YAML formated. description: - File backed cache that uses YAML as a format, the files are per host. version_added: "2.3" author: Brian Coca (@bcoca) ''' # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import codecs import yaml from ansible.parsing.yaml.loader import AnsibleLoader from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.cache import BaseFileCacheModule class CacheModule(BaseFileCacheModule):
""" A caching module backed by yaml files. """ def _load(self, filepath): with codecs.open(filepath, 'r', encoding='utf-8') as f: return AnsibleLoader(f).get_single_data() def _dump(self, value, filepath): with codecs.open(filepath, 'w', encoding='utf-8') as f: yaml.dump(value, f, Dumper=AnsibleDumper, default_flow_style=False)
identifier_body
yaml.py
# (c) 2017, Brian Coca # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ''' DOCUMENTATION: cache: yaml short_description: File backed, YAML formated. description: - File backed cache that uses YAML as a format, the files are per host. version_added: "2.3" author: Brian Coca (@bcoca) ''' # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import codecs import yaml from ansible.parsing.yaml.loader import AnsibleLoader from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.cache import BaseFileCacheModule class CacheModule(BaseFileCacheModule): """ A caching module backed by yaml files. """ def
(self, filepath): with codecs.open(filepath, 'r', encoding='utf-8') as f: return AnsibleLoader(f).get_single_data() def _dump(self, value, filepath): with codecs.open(filepath, 'w', encoding='utf-8') as f: yaml.dump(value, f, Dumper=AnsibleDumper, default_flow_style=False)
_load
identifier_name
feature_anchors.py
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block-relay-only anchors functionality""" import os from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import check_node_connections INBOUND_CONNECTIONS = 5 BLOCK_RELAY_CONNECTIONS = 2 class AnchorsTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.disable_autoconnect = False def run_test(self): node_anchors_path = os.path.join( self.nodes[0].datadir, "regtest", "anchors.dat" ) self.log.info("When node starts, check if anchors.dat doesn't exist") assert not os.path.exists(node_anchors_path) self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node") for i in range(BLOCK_RELAY_CONNECTIONS): self.log.debug(f"block-relay-only: {i}") self.nodes[0].add_outbound_p2p_connection( P2PInterface(), p2p_idx=i, connection_type="block-relay-only" ) self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node") for i in range(INBOUND_CONNECTIONS):
self.log.info("Check node connections") check_node_connections(node=self.nodes[0], num_in=5, num_out=2) # 127.0.0.1 ip = "7f000001" # Since the ip is always 127.0.0.1 for this case, # we store only the port to identify the peers block_relay_nodes_port = [] inbound_nodes_port = [] for p in self.nodes[0].getpeerinfo(): addr_split = p["addr"].split(":") if p["connection_type"] == "block-relay-only": block_relay_nodes_port.append(hex(int(addr_split[1]))[2:]) else: inbound_nodes_port.append(hex(int(addr_split[1]))[2:]) self.log.info("Stop node 0") self.stop_node(0) # It should contain only the block-relay-only addresses self.log.info("Check the addresses in anchors.dat") with open(node_anchors_path, "rb") as file_handler: anchors = file_handler.read().hex() for port in block_relay_nodes_port: ip_port = ip + port assert ip_port in anchors for port in inbound_nodes_port: ip_port = ip + port assert ip_port not in anchors self.log.info("Start node") self.start_node(0) self.log.info("When node starts, check if anchors.dat doesn't exist anymore") assert not os.path.exists(node_anchors_path) if __name__ == "__main__": AnchorsTest().main()
self.log.debug(f"inbound: {i}") self.nodes[0].add_p2p_connection(P2PInterface())
conditional_block
feature_anchors.py
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block-relay-only anchors functionality""" import os from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import check_node_connections INBOUND_CONNECTIONS = 5 BLOCK_RELAY_CONNECTIONS = 2 class AnchorsTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.disable_autoconnect = False def run_test(self): node_anchors_path = os.path.join( self.nodes[0].datadir, "regtest", "anchors.dat" ) self.log.info("When node starts, check if anchors.dat doesn't exist") assert not os.path.exists(node_anchors_path) self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node") for i in range(BLOCK_RELAY_CONNECTIONS): self.log.debug(f"block-relay-only: {i}") self.nodes[0].add_outbound_p2p_connection( P2PInterface(), p2p_idx=i, connection_type="block-relay-only" ) self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node") for i in range(INBOUND_CONNECTIONS): self.log.debug(f"inbound: {i}") self.nodes[0].add_p2p_connection(P2PInterface()) self.log.info("Check node connections")
# Since the ip is always 127.0.0.1 for this case, # we store only the port to identify the peers block_relay_nodes_port = [] inbound_nodes_port = [] for p in self.nodes[0].getpeerinfo(): addr_split = p["addr"].split(":") if p["connection_type"] == "block-relay-only": block_relay_nodes_port.append(hex(int(addr_split[1]))[2:]) else: inbound_nodes_port.append(hex(int(addr_split[1]))[2:]) self.log.info("Stop node 0") self.stop_node(0) # It should contain only the block-relay-only addresses self.log.info("Check the addresses in anchors.dat") with open(node_anchors_path, "rb") as file_handler: anchors = file_handler.read().hex() for port in block_relay_nodes_port: ip_port = ip + port assert ip_port in anchors for port in inbound_nodes_port: ip_port = ip + port assert ip_port not in anchors self.log.info("Start node") self.start_node(0) self.log.info("When node starts, check if anchors.dat doesn't exist anymore") assert not os.path.exists(node_anchors_path) if __name__ == "__main__": AnchorsTest().main()
check_node_connections(node=self.nodes[0], num_in=5, num_out=2) # 127.0.0.1 ip = "7f000001"
random_line_split
feature_anchors.py
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block-relay-only anchors functionality""" import os from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import check_node_connections INBOUND_CONNECTIONS = 5 BLOCK_RELAY_CONNECTIONS = 2 class AnchorsTest(BitcoinTestFramework): def set_test_params(self):
def run_test(self): node_anchors_path = os.path.join( self.nodes[0].datadir, "regtest", "anchors.dat" ) self.log.info("When node starts, check if anchors.dat doesn't exist") assert not os.path.exists(node_anchors_path) self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node") for i in range(BLOCK_RELAY_CONNECTIONS): self.log.debug(f"block-relay-only: {i}") self.nodes[0].add_outbound_p2p_connection( P2PInterface(), p2p_idx=i, connection_type="block-relay-only" ) self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node") for i in range(INBOUND_CONNECTIONS): self.log.debug(f"inbound: {i}") self.nodes[0].add_p2p_connection(P2PInterface()) self.log.info("Check node connections") check_node_connections(node=self.nodes[0], num_in=5, num_out=2) # 127.0.0.1 ip = "7f000001" # Since the ip is always 127.0.0.1 for this case, # we store only the port to identify the peers block_relay_nodes_port = [] inbound_nodes_port = [] for p in self.nodes[0].getpeerinfo(): addr_split = p["addr"].split(":") if p["connection_type"] == "block-relay-only": block_relay_nodes_port.append(hex(int(addr_split[1]))[2:]) else: inbound_nodes_port.append(hex(int(addr_split[1]))[2:]) self.log.info("Stop node 0") self.stop_node(0) # It should contain only the block-relay-only addresses self.log.info("Check the addresses in anchors.dat") with open(node_anchors_path, "rb") as file_handler: anchors = file_handler.read().hex() for port in block_relay_nodes_port: ip_port = ip + port assert ip_port in anchors for port in inbound_nodes_port: ip_port = ip + port assert ip_port not in anchors self.log.info("Start node") self.start_node(0) self.log.info("When node starts, check if anchors.dat doesn't exist anymore") assert not os.path.exists(node_anchors_path) if __name__ == "__main__": AnchorsTest().main()
self.num_nodes = 1 self.disable_autoconnect = False
identifier_body
feature_anchors.py
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block-relay-only anchors functionality""" import os from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import check_node_connections INBOUND_CONNECTIONS = 5 BLOCK_RELAY_CONNECTIONS = 2 class AnchorsTest(BitcoinTestFramework): def
(self): self.num_nodes = 1 self.disable_autoconnect = False def run_test(self): node_anchors_path = os.path.join( self.nodes[0].datadir, "regtest", "anchors.dat" ) self.log.info("When node starts, check if anchors.dat doesn't exist") assert not os.path.exists(node_anchors_path) self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node") for i in range(BLOCK_RELAY_CONNECTIONS): self.log.debug(f"block-relay-only: {i}") self.nodes[0].add_outbound_p2p_connection( P2PInterface(), p2p_idx=i, connection_type="block-relay-only" ) self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node") for i in range(INBOUND_CONNECTIONS): self.log.debug(f"inbound: {i}") self.nodes[0].add_p2p_connection(P2PInterface()) self.log.info("Check node connections") check_node_connections(node=self.nodes[0], num_in=5, num_out=2) # 127.0.0.1 ip = "7f000001" # Since the ip is always 127.0.0.1 for this case, # we store only the port to identify the peers block_relay_nodes_port = [] inbound_nodes_port = [] for p in self.nodes[0].getpeerinfo(): addr_split = p["addr"].split(":") if p["connection_type"] == "block-relay-only": block_relay_nodes_port.append(hex(int(addr_split[1]))[2:]) else: inbound_nodes_port.append(hex(int(addr_split[1]))[2:]) self.log.info("Stop node 0") self.stop_node(0) # It should contain only the block-relay-only addresses self.log.info("Check the addresses in anchors.dat") with open(node_anchors_path, "rb") as file_handler: anchors = file_handler.read().hex() for port in block_relay_nodes_port: ip_port = ip + port assert ip_port in anchors for port in inbound_nodes_port: ip_port = ip + port assert ip_port not in anchors self.log.info("Start node") self.start_node(0) self.log.info("When node starts, check if anchors.dat doesn't exist anymore") assert not os.path.exists(node_anchors_path) if __name__ == "__main__": AnchorsTest().main()
set_test_params
identifier_name
lib.rs
//! Board Support Crate for the bluepill //! //! # Usage //! //! Follow `cortex-m-quickstart` [instructions][i] but remove the `memory.x` //! linker script and the `build.rs` build script file as part of the //! configuration of the quickstart crate. Additionally, uncomment the "if using //! ITM" block in the `.gdbinit` file. //! //! [i]: https://docs.rs/cortex-m-quickstart/0.1.1/cortex_m_quickstart/ //! //! # Examples //! //! Check the [examples] module. //! //! [examples]: ./examples/index.html #![deny(missing_docs)] //#![deny(warnings)] #![no_std] #![feature(associated_type_defaults)] extern crate cast; pub extern crate stm32f103xx; extern crate hal; // For documentation only pub mod examples; pub mod led; //pub mod serial; pub mod timer; pub mod clock; pub mod pin;
pub mod serial; pub mod frequency;
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serde_macros)] #![deny(unsafe_code)] extern crate heapsize; extern crate num_traits; extern crate rustc_serialize; extern crate serde; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn
() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?} .. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
one
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serde_macros)] #![deny(unsafe_code)] extern crate heapsize; extern crate num_traits; extern crate rustc_serialize; extern crate serde; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?} .. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I)
#[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
{ self.begin = begin; self.length = length; }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serde_macros)] #![deny(unsafe_code)] extern crate heapsize; extern crate num_traits; extern crate rustc_serialize; extern crate serde; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline]
} impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?} .. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) }
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serde_macros)] #![deny(unsafe_code)] extern crate heapsize; extern crate num_traits; extern crate rustc_serialize; extern crate serde; use std::cmp::{self, max, min}; use std::fmt; use std::iter; use std::marker::PhantomData; use std::ops; pub trait Int: Copy + ops::Add<Self, Output=Self> + ops::Sub<Self, Output=Self> + cmp::Ord { fn zero() -> Self; fn one() -> Self; fn max_value() -> Self; fn from_usize(n: usize) -> Option<Self>; } impl Int for isize { #[inline] fn zero() -> isize { 0 } #[inline] fn one() -> isize { 1 } #[inline] fn max_value() -> isize { ::std::isize::MAX } #[inline] fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) } } impl Int for usize { #[inline] fn zero() -> usize { 0 } #[inline] fn one() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Index; } impl RangeIndex for isize { type Index = isize; #[inline] fn new(x: isize) -> isize { x } #[inline] fn get(self) -> isize { self } } impl RangeIndex for usize { type Index = usize; #[inline] fn new(x: usize) -> usize { x } #[inline] fn get(self) -> usize { self } } /// Implements a range index type with operator overloads #[macro_export] macro_rules! int_range_index { ($(#[$attr:meta])* struct $Self_:ident($T:ty)) => ( #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)] $(#[$attr])* pub struct $Self_(pub $T); impl $Self_ { #[inline] pub fn to_usize(self) -> usize { self.get() as usize } } impl RangeIndex for $Self_ { type Index = $T; #[inline] fn new(x: $T) -> $Self_ { $Self_(x) } #[inline] fn get(self) -> $T { match self { $Self_(x) => x } } } impl $crate::Int for $Self_ { #[inline] fn zero() -> $Self_ { $Self_($crate::Int::zero()) } #[inline] fn one() -> $Self_ { $Self_($crate::Int::one()) } #[inline] fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) } #[inline] fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) } } impl ::std::ops::Add<$Self_> for $Self_ { type Output = $Self_; #[inline] fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) } } impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; #[inline] fn neg(self) -> $Self_ { $Self_(-self.get()) } } ) } /// A range of indices #[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)] pub struct Range<I> { begin: I, length: I, } impl<I: RangeIndex> fmt::Debug for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{:?} .. {:?})", self.begin(), self.end()) } } /// An iterator over each index in a range pub struct EachIndex<T, I> { it: ops::Range<T>, phantom: PhantomData<I>, } pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> { EachIndex { it: start.get()..stop.get(), phantom: PhantomData } } impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I> where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> { type Item = I; #[inline] fn next(&mut self) -> Option<I> { self.it.next().map(RangeIndex::new) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } impl<I: RangeIndex> Range<I> { /// Create a new range from beginning and length offsets. This could be /// denoted as `[begin, begin + length)`. /// /// ~~~ignore /// |-- begin ->|-- length ->| /// | | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn new(begin: I, length: I) -> Range<I> { Range { begin: begin, length: length } } #[inline] pub fn empty() -> Range<I> { Range::new(Int::zero(), Int::zero()) } /// The index offset to the beginning of the range. /// /// ~~~ignore /// |-- begin ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn begin(&self) -> I { self.begin } /// The index offset from the beginning to the end of the range. /// /// ~~~ignore /// |-- length ->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn length(&self) -> I { self.length } /// The index offset to the end of the range. /// /// ~~~ignore /// |--------- end --------->| /// | | /// <- o - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn end(&self) -> I { self.begin + self.length } /// `true` if the index is between the beginning and the end of the range. /// /// ~~~ignore /// false true false /// | | | /// <- o - - + - - +=====+======+ - + - -> /// ~~~ #[inline] pub fn contains(&self, i: I) -> bool { i >= self.begin() && i < self.end() } /// `true` if the offset from the beginning to the end of the range is zero. #[inline] pub fn is_empty(&self) -> bool { self.length() == Int::zero() } /// Shift the entire range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - +============+ - - - - - | - - - -> /// | /// <- o - - - - - - - +============+ - - - -> /// ~~~ #[inline] pub fn shift_by(&mut self, delta: I) { self.begin = self.begin + delta; } /// Extend the end of the range by the supplied index delta. /// /// ~~~ignore /// |-- delta ->| /// | | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_by(&mut self, delta: I) { self.length = self.length + delta; } /// Move the end of the range to the target index. /// /// ~~~ignore /// target /// | /// <- o - - - - - +====+ - - - - - | - - - -> /// | /// <- o - - - - - +================+ - - - -> /// ~~~ #[inline] pub fn extend_to(&mut self, target: I) { self.length = target - self.begin; } /// Adjust the beginning offset and the length by the supplied deltas. #[inline] pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) { self.begin = self.begin + begin_delta; self.length = self.length + length_delta; } /// Set the begin and length values. #[inline] pub fn reset(&mut self, begin: I, length: I) { self.begin = begin; self.length = length; } #[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin
else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { each_index(self.begin(), self.end()) } }
{ Range::empty() }
conditional_block
http-errors_v1.x.x.js
// flow-typed signature: 573c576fe34eb3c3c65dd7a9c90a46d2 // flow-typed version: b43dff3e0e/http-errors_v1.x.x/flow_>=v0.25.x declare module 'http-errors' { declare class
extends HttpError { constructor(): SpecialHttpError; } declare class HttpError extends Error { expose: bool; message: string; status: number; statusCode: number; } declare module.exports: { (status?: number, message?: string, props?: Object): HttpError; HttpError: typeof HttpError; BadRequest: typeof SpecialHttpError; Unauthorized: typeof SpecialHttpError; PaymentRequired: typeof SpecialHttpError; Forbidden: typeof SpecialHttpError; NotFound: typeof SpecialHttpError; MethodNotAllowed: typeof SpecialHttpError; NotAcceptable: typeof SpecialHttpError; ProxyAuthenticationRequired: typeof SpecialHttpError; RequestTimeout: typeof SpecialHttpError; Conflict: typeof SpecialHttpError; Gone: typeof SpecialHttpError; LengthRequired: typeof SpecialHttpError; PreconditionFailed: typeof SpecialHttpError; PayloadTooLarge: typeof SpecialHttpError; URITooLong: typeof SpecialHttpError; UnsupportedMediaType: typeof SpecialHttpError; RangeNotStatisfiable: typeof SpecialHttpError; ExpectationFailed: typeof SpecialHttpError; ImATeapot: typeof SpecialHttpError; MisdirectedRequest: typeof SpecialHttpError; UnprocessableEntity: typeof SpecialHttpError; Locked: typeof SpecialHttpError; FailedDependency: typeof SpecialHttpError; UnorderedCollection: typeof SpecialHttpError; UpgradeRequired: typeof SpecialHttpError; PreconditionRequired: typeof SpecialHttpError; TooManyRequests: typeof SpecialHttpError; RequestHeaderFieldsTooLarge: typeof SpecialHttpError; UnavailableForLegalReasons: typeof SpecialHttpError; InternalServerError: typeof SpecialHttpError; NotImplemented: typeof SpecialHttpError; BadGateway: typeof SpecialHttpError; ServiceUnavailable: typeof SpecialHttpError; GatewayTimeout: typeof SpecialHttpError; HTTPVersionNotSupported: typeof SpecialHttpError; VariantAlsoNegotiates: typeof SpecialHttpError; InsufficientStorage: typeof SpecialHttpError; LoopDetected: typeof SpecialHttpError; BandwidthLimitExceeded: typeof SpecialHttpError; NotExtended: typeof SpecialHttpError; NetworkAuthenticationRequired: typeof SpecialHttpError; } }
SpecialHttpError
identifier_name
http-errors_v1.x.x.js
// flow-typed signature: 573c576fe34eb3c3c65dd7a9c90a46d2 // flow-typed version: b43dff3e0e/http-errors_v1.x.x/flow_>=v0.25.x declare module 'http-errors' { declare class SpecialHttpError extends HttpError { constructor(): SpecialHttpError; } declare class HttpError extends Error { expose: bool; message: string; status: number; statusCode: number; } declare module.exports: { (status?: number, message?: string, props?: Object): HttpError; HttpError: typeof HttpError; BadRequest: typeof SpecialHttpError; Unauthorized: typeof SpecialHttpError; PaymentRequired: typeof SpecialHttpError; Forbidden: typeof SpecialHttpError; NotFound: typeof SpecialHttpError; MethodNotAllowed: typeof SpecialHttpError; NotAcceptable: typeof SpecialHttpError; ProxyAuthenticationRequired: typeof SpecialHttpError; RequestTimeout: typeof SpecialHttpError; Conflict: typeof SpecialHttpError; Gone: typeof SpecialHttpError; LengthRequired: typeof SpecialHttpError; PreconditionFailed: typeof SpecialHttpError; PayloadTooLarge: typeof SpecialHttpError; URITooLong: typeof SpecialHttpError; UnsupportedMediaType: typeof SpecialHttpError; RangeNotStatisfiable: typeof SpecialHttpError; ExpectationFailed: typeof SpecialHttpError; ImATeapot: typeof SpecialHttpError; MisdirectedRequest: typeof SpecialHttpError; UnprocessableEntity: typeof SpecialHttpError; Locked: typeof SpecialHttpError; FailedDependency: typeof SpecialHttpError; UnorderedCollection: typeof SpecialHttpError; UpgradeRequired: typeof SpecialHttpError; PreconditionRequired: typeof SpecialHttpError; TooManyRequests: typeof SpecialHttpError; RequestHeaderFieldsTooLarge: typeof SpecialHttpError; UnavailableForLegalReasons: typeof SpecialHttpError;
ServiceUnavailable: typeof SpecialHttpError; GatewayTimeout: typeof SpecialHttpError; HTTPVersionNotSupported: typeof SpecialHttpError; VariantAlsoNegotiates: typeof SpecialHttpError; InsufficientStorage: typeof SpecialHttpError; LoopDetected: typeof SpecialHttpError; BandwidthLimitExceeded: typeof SpecialHttpError; NotExtended: typeof SpecialHttpError; NetworkAuthenticationRequired: typeof SpecialHttpError; } }
InternalServerError: typeof SpecialHttpError; NotImplemented: typeof SpecialHttpError; BadGateway: typeof SpecialHttpError;
random_line_split
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 { (&self.string).as_ptr() } #[inline] pub fn as_mut_ptr(&mut self) -> *mut u8 { &mut self.string as *mut str as *mut u8 } #[inline] pub fn as_str(&self) -> &str { &self.string } #[inline] pub fn as_mut_str(&mut self) -> &mut str { &mut self.string } #[inline] pub fn as_bytes(&self) -> &[u8] { self.string.as_bytes() } pub fn as_cstr(&self) -> Result<Cow<CStr>, InteriorNullError> { unimplemented!() } #[inline] pub fn len(&self) -> usize { self.string.len() } #[inline] pub fn is_empty(&self) -> bool { self.string.is_empty() } #[inline] pub fn
(&self) -> bool { self.len() == PASCAL_STRING_BUF_SIZE } #[inline] pub fn chars(&self) -> Chars { self.string.chars() } #[inline] pub fn bytes(&self) -> Bytes { self.string.bytes() } #[inline] pub fn lines(&self) -> Lines { self.string.lines() } } impl<S: AsRef<str> + ?Sized> PartialEq<S> for PascalStr { #[inline] fn eq(&self, other: &S) -> bool { let other = other.as_ref(); self.as_str() == other } } impl<S: AsRef<str> + ?Sized> PartialOrd<S> for PascalStr { #[inline] fn partial_cmp(&self, other: &S) -> Option<Ordering> { let other = other.as_ref(); self.as_str().partial_cmp(&other) } } impl ToOwned for PascalStr { type Owned = PascalString; #[inline] fn to_owned(&self) -> Self::Owned { PascalString::from_str(self.as_str()).unwrap() } } impl AsRef<str> for PascalStr { #[inline] fn as_ref(&self) -> &str { &self.string } } pub type Chars<'a> = str::Chars<'a>; pub type Bytes<'a> = str::Bytes<'a>; pub type Lines<'a> = str::Lines<'a>; pub struct InteriorNullError;
is_full
identifier_name
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 { (&self.string).as_ptr() } #[inline] pub fn as_mut_ptr(&mut self) -> *mut u8 { &mut self.string as *mut str as *mut u8 } #[inline] pub fn as_str(&self) -> &str { &self.string } #[inline] pub fn as_mut_str(&mut self) -> &mut str { &mut self.string } #[inline] pub fn as_bytes(&self) -> &[u8] { self.string.as_bytes() } pub fn as_cstr(&self) -> Result<Cow<CStr>, InteriorNullError> { unimplemented!() } #[inline] pub fn len(&self) -> usize { self.string.len() } #[inline] pub fn is_empty(&self) -> bool { self.string.is_empty() } #[inline] pub fn is_full(&self) -> bool
#[inline] pub fn chars(&self) -> Chars { self.string.chars() } #[inline] pub fn bytes(&self) -> Bytes { self.string.bytes() } #[inline] pub fn lines(&self) -> Lines { self.string.lines() } } impl<S: AsRef<str> + ?Sized> PartialEq<S> for PascalStr { #[inline] fn eq(&self, other: &S) -> bool { let other = other.as_ref(); self.as_str() == other } } impl<S: AsRef<str> + ?Sized> PartialOrd<S> for PascalStr { #[inline] fn partial_cmp(&self, other: &S) -> Option<Ordering> { let other = other.as_ref(); self.as_str().partial_cmp(&other) } } impl ToOwned for PascalStr { type Owned = PascalString; #[inline] fn to_owned(&self) -> Self::Owned { PascalString::from_str(self.as_str()).unwrap() } } impl AsRef<str> for PascalStr { #[inline] fn as_ref(&self) -> &str { &self.string } } pub type Chars<'a> = str::Chars<'a>; pub type Bytes<'a> = str::Bytes<'a>; pub type Lines<'a> = str::Lines<'a>; pub struct InteriorNullError;
{ self.len() == PASCAL_STRING_BUF_SIZE }
identifier_body
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 { (&self.string).as_ptr() } #[inline] pub fn as_mut_ptr(&mut self) -> *mut u8 { &mut self.string as *mut str as *mut u8 } #[inline] pub fn as_str(&self) -> &str { &self.string } #[inline] pub fn as_mut_str(&mut self) -> &mut str { &mut self.string } #[inline] pub fn as_bytes(&self) -> &[u8] { self.string.as_bytes() } pub fn as_cstr(&self) -> Result<Cow<CStr>, InteriorNullError> { unimplemented!() } #[inline] pub fn len(&self) -> usize { self.string.len() } #[inline] pub fn is_empty(&self) -> bool { self.string.is_empty() } #[inline] pub fn is_full(&self) -> bool { self.len() == PASCAL_STRING_BUF_SIZE } #[inline] pub fn chars(&self) -> Chars { self.string.chars() } #[inline] pub fn bytes(&self) -> Bytes { self.string.bytes() } #[inline] pub fn lines(&self) -> Lines { self.string.lines() } } impl<S: AsRef<str> + ?Sized> PartialEq<S> for PascalStr { #[inline] fn eq(&self, other: &S) -> bool { let other = other.as_ref(); self.as_str() == other } } impl<S: AsRef<str> + ?Sized> PartialOrd<S> for PascalStr { #[inline] fn partial_cmp(&self, other: &S) -> Option<Ordering> { let other = other.as_ref(); self.as_str().partial_cmp(&other) } } impl ToOwned for PascalStr { type Owned = PascalString;
} } impl AsRef<str> for PascalStr { #[inline] fn as_ref(&self) -> &str { &self.string } } pub type Chars<'a> = str::Chars<'a>; pub type Bytes<'a> = str::Bytes<'a>; pub type Lines<'a> = str::Lines<'a>; pub struct InteriorNullError;
#[inline] fn to_owned(&self) -> Self::Owned { PascalString::from_str(self.as_str()).unwrap()
random_line_split
fraction-circle.ts
import {BaseCircle} from "../base-class/base-circle"; import SvgTags from "../base-class/svg-tags"; import SvgTagsHelper from "../helper/svg-tags-helper"; import {IAvailableOptions} from "../interface/iavailable-options"; import {ISize} from "../interface/isize"; /** * Every circle gets dynamically called by the given type in the options object example: { type: 'PlainCircle' } */ class FractionCircle extends BaseCircle { private coordinates = { x: 0, y: 0, }; private fractionAngle: number; private rotateDegree: number; protected radius: number; protected additionalCssClasses: IAvailableOptions["additionalCssClasses"] = {}; private static isOdd(count: number) { return count % 2; } /** * @inheritDoc */ public initialize(options: IAvailableOptions, size: ISize) { super.initialize(options, size); const maxSize = this.size.maxSize; this.coordinates = { x: maxSize / 2, y: maxSize / 2, }; this.radius = maxSize / 2.2; if (this.options.additionalCssClasses)
this.animateInView(); } /** * @inheritDoc */ public drawCircle() { this.drawContainer(); this.drawFraction(); this.append(); } /** * @description Draws the arc parts by given fraction count */ public drawFraction() { this.fractionAngle = 360 / this.options.fractionCount; for (let i = 0; i < this.options.fractionCount; i++) { this.rotateDegree = this.fractionAngle * i; let fillColor = this.options.fillColor; if (this.options.fractionColors && this.options.fractionColors.length >= 2) { const color = this.options.fractionColors; fillColor = FractionCircle.isOdd(i) ? color[0] : color[1]; } if (i >= this.options.fractionFilledCount) { fillColor = "none"; } this.drawArc(fillColor); } } private drawArc(fillColor: string): void { const arc = SvgTags.addArc({ "id": `arc-${this.options.id}`, "class": `fraction`, "d": SvgTagsHelper.describeArc( this.coordinates.x, this.coordinates.y, this.radius, 0, this.fractionAngle, ) + this.getLineToCenter(), "stroke-width": this.options.foregroundCircleWidth, "fill": fillColor, "stroke": this.options.strokeColor, "transform": `rotate(${this.rotateDegree}, ${this.coordinates.x}, ${this.coordinates.y})`, }); this.tags.push({ element: arc, parentId: `svg-${this.options.id}`, }); } public getLineToCenter(): string { const pathEndCoordinates = SvgTagsHelper.calculatePathEndCoordinates( this.coordinates.x, this.coordinates.y, this.radius, this.fractionAngle, ); return ` L ${this.coordinates.y} ${this.coordinates.x} M ${pathEndCoordinates.x} ${pathEndCoordinates.y} L ${this.coordinates.y} ${this.coordinates.x}`; } public animate(element: Element): void { } } export default FractionCircle;
{ this.additionalCssClasses = this.options.additionalCssClasses; }
conditional_block
fraction-circle.ts
import {BaseCircle} from "../base-class/base-circle"; import SvgTags from "../base-class/svg-tags"; import SvgTagsHelper from "../helper/svg-tags-helper"; import {IAvailableOptions} from "../interface/iavailable-options"; import {ISize} from "../interface/isize"; /** * Every circle gets dynamically called by the given type in the options object example: { type: 'PlainCircle' } */ class FractionCircle extends BaseCircle { private coordinates = { x: 0,
y: 0, }; private fractionAngle: number; private rotateDegree: number; protected radius: number; protected additionalCssClasses: IAvailableOptions["additionalCssClasses"] = {}; private static isOdd(count: number) { return count % 2; } /** * @inheritDoc */ public initialize(options: IAvailableOptions, size: ISize) { super.initialize(options, size); const maxSize = this.size.maxSize; this.coordinates = { x: maxSize / 2, y: maxSize / 2, }; this.radius = maxSize / 2.2; if (this.options.additionalCssClasses) { this.additionalCssClasses = this.options.additionalCssClasses; } this.animateInView(); } /** * @inheritDoc */ public drawCircle() { this.drawContainer(); this.drawFraction(); this.append(); } /** * @description Draws the arc parts by given fraction count */ public drawFraction() { this.fractionAngle = 360 / this.options.fractionCount; for (let i = 0; i < this.options.fractionCount; i++) { this.rotateDegree = this.fractionAngle * i; let fillColor = this.options.fillColor; if (this.options.fractionColors && this.options.fractionColors.length >= 2) { const color = this.options.fractionColors; fillColor = FractionCircle.isOdd(i) ? color[0] : color[1]; } if (i >= this.options.fractionFilledCount) { fillColor = "none"; } this.drawArc(fillColor); } } private drawArc(fillColor: string): void { const arc = SvgTags.addArc({ "id": `arc-${this.options.id}`, "class": `fraction`, "d": SvgTagsHelper.describeArc( this.coordinates.x, this.coordinates.y, this.radius, 0, this.fractionAngle, ) + this.getLineToCenter(), "stroke-width": this.options.foregroundCircleWidth, "fill": fillColor, "stroke": this.options.strokeColor, "transform": `rotate(${this.rotateDegree}, ${this.coordinates.x}, ${this.coordinates.y})`, }); this.tags.push({ element: arc, parentId: `svg-${this.options.id}`, }); } public getLineToCenter(): string { const pathEndCoordinates = SvgTagsHelper.calculatePathEndCoordinates( this.coordinates.x, this.coordinates.y, this.radius, this.fractionAngle, ); return ` L ${this.coordinates.y} ${this.coordinates.x} M ${pathEndCoordinates.x} ${pathEndCoordinates.y} L ${this.coordinates.y} ${this.coordinates.x}`; } public animate(element: Element): void { } } export default FractionCircle;
random_line_split
fraction-circle.ts
import {BaseCircle} from "../base-class/base-circle"; import SvgTags from "../base-class/svg-tags"; import SvgTagsHelper from "../helper/svg-tags-helper"; import {IAvailableOptions} from "../interface/iavailable-options"; import {ISize} from "../interface/isize"; /** * Every circle gets dynamically called by the given type in the options object example: { type: 'PlainCircle' } */ class FractionCircle extends BaseCircle { private coordinates = { x: 0, y: 0, }; private fractionAngle: number; private rotateDegree: number; protected radius: number; protected additionalCssClasses: IAvailableOptions["additionalCssClasses"] = {}; private static isOdd(count: number) { return count % 2; } /** * @inheritDoc */ public initialize(options: IAvailableOptions, size: ISize) { super.initialize(options, size); const maxSize = this.size.maxSize; this.coordinates = { x: maxSize / 2, y: maxSize / 2, }; this.radius = maxSize / 2.2; if (this.options.additionalCssClasses) { this.additionalCssClasses = this.options.additionalCssClasses; } this.animateInView(); } /** * @inheritDoc */ public drawCircle() { this.drawContainer(); this.drawFraction(); this.append(); } /** * @description Draws the arc parts by given fraction count */ public drawFraction() { this.fractionAngle = 360 / this.options.fractionCount; for (let i = 0; i < this.options.fractionCount; i++) { this.rotateDegree = this.fractionAngle * i; let fillColor = this.options.fillColor; if (this.options.fractionColors && this.options.fractionColors.length >= 2) { const color = this.options.fractionColors; fillColor = FractionCircle.isOdd(i) ? color[0] : color[1]; } if (i >= this.options.fractionFilledCount) { fillColor = "none"; } this.drawArc(fillColor); } } private drawArc(fillColor: string): void { const arc = SvgTags.addArc({ "id": `arc-${this.options.id}`, "class": `fraction`, "d": SvgTagsHelper.describeArc( this.coordinates.x, this.coordinates.y, this.radius, 0, this.fractionAngle, ) + this.getLineToCenter(), "stroke-width": this.options.foregroundCircleWidth, "fill": fillColor, "stroke": this.options.strokeColor, "transform": `rotate(${this.rotateDegree}, ${this.coordinates.x}, ${this.coordinates.y})`, }); this.tags.push({ element: arc, parentId: `svg-${this.options.id}`, }); } public getLineToCenter(): string { const pathEndCoordinates = SvgTagsHelper.calculatePathEndCoordinates( this.coordinates.x, this.coordinates.y, this.radius, this.fractionAngle, ); return ` L ${this.coordinates.y} ${this.coordinates.x} M ${pathEndCoordinates.x} ${pathEndCoordinates.y} L ${this.coordinates.y} ${this.coordinates.x}`; } public
(element: Element): void { } } export default FractionCircle;
animate
identifier_name
__main__.py
import ast import heisenberg.library.heisenberg_dynamics_context import heisenberg.library.orbit_plot import heisenberg.option_parser import heisenberg.plot import heisenberg.util import matplotlib import numpy as np import sys # https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell block limit" problems matplotlib.rcParams['agg.path.chunksize'] = 10000 dynamics_context = heisenberg.library.heisenberg_dynamics_context.Numeric() op = heisenberg.option_parser.OptionParser(module=heisenberg.plot) # Add the subprogram-specific options here. op.add_option( '--initial-preimage', dest='initial_preimage', type='string', help='Specifies the preimage of the initial conditions with respect to the embedding map specified by the --embedding-dimension and --embedding-solution-sheet-index option values. Should have the form [x_1,...,x_n], where n is the embedding dimension and x_i is a floating point literal for each i.' ) op.add_option( '--initial', dest='initial', type='string', help='Specifies the initial conditions [x,y,z,p_x,p_y,p_z], where each of x,y,z,p_x,p_y,p_z are floating point literals.' ) op.add_option( '--optimization-iterations', dest='optimization_iterations', default=1000, type='int', help='Specifies the number of iterations to run the optimization for (if applicable). Default is 1000.' ) op.add_option( '--optimize-initial', dest='optimize_initial', action='store_true', default=False, help='Indicates that the specified initial condition (via whichever of the --initial... options) should be used as the starting point for an optimization to attempt to close the orbit. Default value is False.' ) op.add_option( '--output-dir', dest='output_dir', default='.', help='Specifies the directory to write plot images and data files to. Default is current directory.' ) op.add_option( '--disable-plot-initial', dest='disable_plot_initial', action='store_true', default=False, help='Disables plotting the initial curve; only has effect if --optimize-initial is specified.' ) options,args = op.parse_argv_and_validate() if options is None: sys.exit(-1) num_initial_conditions_specified = sum([ options.initial_preimage is not None, options.initial is not None, ]) if num_initial_conditions_specified != 1: print('Some initial condition option must be specified; --initial-preimage, --initial. However, {0} of those were specified.'.format(num_initial_conditions_specified)) op.print_help() sys.exit(-1) # Validate subprogram-specific options here. # Attempt to parse initial conditions. Upon success, the attribute options.qp_0 should exist. if options.initial_preimage is not None:
elif options.initial is not None: try: options.initial = heisenberg.util.csv_as_ndarray(heisenberg.util.pop_brackets_off_of(options.initial), float) expected_shape = (6,) if options.initial.shape != expected_shape: raise ValueError('--initial value had the wrong number of components (got {0} but expected {1}).'.format(options.initial.shape, expected_shape)) options.qp_0 = options.initial.reshape(2,3) except ValueError as e: print('error parsing --initial value: {0}'.format(str(e))) op.print_help() sys.exit(-1) else: assert False, 'this should never happen because of the check with num_initial_conditions_specified' rng = np.random.RandomState(options.seed) heisenberg.plot.plot(dynamics_context, options, rng=rng)
try: options.initial_preimage = np.array(ast.literal_eval(options.initial_preimage)) expected_shape = (options.embedding_dimension,) if options.initial_preimage.shape != expected_shape: raise ValueError('--initial-preimage value had the wrong number of components (got {0} but expected {1}).'.format(options.initial_preimage.shape, expected_shape)) options.qp_0 = dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)(options.initial_preimage) except Exception as e: print('error parsing --initial-preimage value; error was {0}'.format(e)) op.print_help() sys.exit(-1)
conditional_block
__main__.py
import ast import heisenberg.library.heisenberg_dynamics_context import heisenberg.library.orbit_plot import heisenberg.option_parser import heisenberg.plot import heisenberg.util import matplotlib import numpy as np import sys # https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell block limit" problems matplotlib.rcParams['agg.path.chunksize'] = 10000 dynamics_context = heisenberg.library.heisenberg_dynamics_context.Numeric() op = heisenberg.option_parser.OptionParser(module=heisenberg.plot) # Add the subprogram-specific options here. op.add_option( '--initial-preimage', dest='initial_preimage', type='string', help='Specifies the preimage of the initial conditions with respect to the embedding map specified by the --embedding-dimension and --embedding-solution-sheet-index option values. Should have the form [x_1,...,x_n], where n is the embedding dimension and x_i is a floating point literal for each i.' ) op.add_option( '--initial', dest='initial', type='string', help='Specifies the initial conditions [x,y,z,p_x,p_y,p_z], where each of x,y,z,p_x,p_y,p_z are floating point literals.' ) op.add_option( '--optimization-iterations', dest='optimization_iterations', default=1000, type='int', help='Specifies the number of iterations to run the optimization for (if applicable). Default is 1000.' ) op.add_option( '--optimize-initial', dest='optimize_initial', action='store_true', default=False, help='Indicates that the specified initial condition (via whichever of the --initial... options) should be used as the starting point for an optimization to attempt to close the orbit. Default value is False.' ) op.add_option( '--output-dir', dest='output_dir', default='.', help='Specifies the directory to write plot images and data files to. Default is current directory.' ) op.add_option( '--disable-plot-initial', dest='disable_plot_initial', action='store_true', default=False, help='Disables plotting the initial curve; only has effect if --optimize-initial is specified.' ) options,args = op.parse_argv_and_validate() if options is None: sys.exit(-1) num_initial_conditions_specified = sum([ options.initial_preimage is not None, options.initial is not None, ]) if num_initial_conditions_specified != 1: print('Some initial condition option must be specified; --initial-preimage, --initial. However, {0} of those were specified.'.format(num_initial_conditions_specified)) op.print_help() sys.exit(-1) # Validate subprogram-specific options here. # Attempt to parse initial conditions. Upon success, the attribute options.qp_0 should exist. if options.initial_preimage is not None: try: options.initial_preimage = np.array(ast.literal_eval(options.initial_preimage)) expected_shape = (options.embedding_dimension,) if options.initial_preimage.shape != expected_shape: raise ValueError('--initial-preimage value had the wrong number of components (got {0} but expected {1}).'.format(options.initial_preimage.shape, expected_shape)) options.qp_0 = dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)(options.initial_preimage) except Exception as e: print('error parsing --initial-preimage value; error was {0}'.format(e)) op.print_help() sys.exit(-1) elif options.initial is not None: try: options.initial = heisenberg.util.csv_as_ndarray(heisenberg.util.pop_brackets_off_of(options.initial), float) expected_shape = (6,) if options.initial.shape != expected_shape: raise ValueError('--initial value had the wrong number of components (got {0} but expected {1}).'.format(options.initial.shape, expected_shape))
except ValueError as e: print('error parsing --initial value: {0}'.format(str(e))) op.print_help() sys.exit(-1) else: assert False, 'this should never happen because of the check with num_initial_conditions_specified' rng = np.random.RandomState(options.seed) heisenberg.plot.plot(dynamics_context, options, rng=rng)
options.qp_0 = options.initial.reshape(2,3)
random_line_split
__init__.py
# -*- Mode: Python -*- import socket import unittest __version__ = '0.1.1' from .cys2n import * protocol_version_map = { 'SSLv2' : 20, 'SSLv3' : 30, 'TLS10' : 31, 'TLS11' : 32, 'TLS12' : 33, } class PROTOCOL: reverse_map = {} for name, val in protocol_version_map.items(): setattr (PROTOCOL, name, val) PROTOCOL.reverse_map[val] = name class s2n_socket: def __init__ (self, cfg, pysock, conn=None): self.cfg = cfg self.sock = pysock self.fd = pysock.fileno() self.conn = conn self.negotiated = False def __repr__ (self):
def bind (self, *args, **kwargs): return self.sock.bind (*args, **kwargs) def listen (self, *args, **kwargs): return self.sock.listen (*args, **kwargs) def accept (self): sock, addr = self.sock.accept() conn = Connection (MODE.SERVER) conn.set_config (self.cfg) conn.set_fd (sock.fileno()) # XXX verify new = self.__class__ (self.cfg, sock, conn) return new, addr # XXX client mode as yet untested. def connect (self, addr): self.sock.connect (addr) self.conn = Connection (MODE.CLIENT) self.conn.set_config (self.cfg) self.conn.set_fd (self.fd) def _check_negotiated (self): if not self.negotiated: self.negotiate() def negotiate (self): if not self.negotiated: self.conn.negotiate() self.negotiated = True def recv (self, block_size): self._check_negotiated() r = [] left = block_size while left: b, more = self.conn.recv (left) r.append (b) if not more: break else: left -= len(b) return b''.join (r) def send (self, data): self._check_negotiated() pos = 0 left = len(data) while left: n, more = self.conn.send (data, pos) pos += n if not more: break else: pass left -= n return pos def shutdown (self, how=None): more = 1 while more: more = self.conn.shutdown() def close (self): try: self.shutdown() finally: self.sock.close()
return '<s2n sock=%r conn=%r @%x>' % (self.sock, self.conn, id (self))
identifier_body
__init__.py
# -*- Mode: Python -*-
__version__ = '0.1.1' from .cys2n import * protocol_version_map = { 'SSLv2' : 20, 'SSLv3' : 30, 'TLS10' : 31, 'TLS11' : 32, 'TLS12' : 33, } class PROTOCOL: reverse_map = {} for name, val in protocol_version_map.items(): setattr (PROTOCOL, name, val) PROTOCOL.reverse_map[val] = name class s2n_socket: def __init__ (self, cfg, pysock, conn=None): self.cfg = cfg self.sock = pysock self.fd = pysock.fileno() self.conn = conn self.negotiated = False def __repr__ (self): return '<s2n sock=%r conn=%r @%x>' % (self.sock, self.conn, id (self)) def bind (self, *args, **kwargs): return self.sock.bind (*args, **kwargs) def listen (self, *args, **kwargs): return self.sock.listen (*args, **kwargs) def accept (self): sock, addr = self.sock.accept() conn = Connection (MODE.SERVER) conn.set_config (self.cfg) conn.set_fd (sock.fileno()) # XXX verify new = self.__class__ (self.cfg, sock, conn) return new, addr # XXX client mode as yet untested. def connect (self, addr): self.sock.connect (addr) self.conn = Connection (MODE.CLIENT) self.conn.set_config (self.cfg) self.conn.set_fd (self.fd) def _check_negotiated (self): if not self.negotiated: self.negotiate() def negotiate (self): if not self.negotiated: self.conn.negotiate() self.negotiated = True def recv (self, block_size): self._check_negotiated() r = [] left = block_size while left: b, more = self.conn.recv (left) r.append (b) if not more: break else: left -= len(b) return b''.join (r) def send (self, data): self._check_negotiated() pos = 0 left = len(data) while left: n, more = self.conn.send (data, pos) pos += n if not more: break else: pass left -= n return pos def shutdown (self, how=None): more = 1 while more: more = self.conn.shutdown() def close (self): try: self.shutdown() finally: self.sock.close()
import socket import unittest
random_line_split
__init__.py
# -*- Mode: Python -*- import socket import unittest __version__ = '0.1.1' from .cys2n import * protocol_version_map = { 'SSLv2' : 20, 'SSLv3' : 30, 'TLS10' : 31, 'TLS11' : 32, 'TLS12' : 33, } class PROTOCOL: reverse_map = {} for name, val in protocol_version_map.items(): setattr (PROTOCOL, name, val) PROTOCOL.reverse_map[val] = name class s2n_socket: def __init__ (self, cfg, pysock, conn=None): self.cfg = cfg self.sock = pysock self.fd = pysock.fileno() self.conn = conn self.negotiated = False def __repr__ (self): return '<s2n sock=%r conn=%r @%x>' % (self.sock, self.conn, id (self)) def bind (self, *args, **kwargs): return self.sock.bind (*args, **kwargs) def listen (self, *args, **kwargs): return self.sock.listen (*args, **kwargs) def accept (self): sock, addr = self.sock.accept() conn = Connection (MODE.SERVER) conn.set_config (self.cfg) conn.set_fd (sock.fileno()) # XXX verify new = self.__class__ (self.cfg, sock, conn) return new, addr # XXX client mode as yet untested. def connect (self, addr): self.sock.connect (addr) self.conn = Connection (MODE.CLIENT) self.conn.set_config (self.cfg) self.conn.set_fd (self.fd) def _check_negotiated (self): if not self.negotiated: self.negotiate() def
(self): if not self.negotiated: self.conn.negotiate() self.negotiated = True def recv (self, block_size): self._check_negotiated() r = [] left = block_size while left: b, more = self.conn.recv (left) r.append (b) if not more: break else: left -= len(b) return b''.join (r) def send (self, data): self._check_negotiated() pos = 0 left = len(data) while left: n, more = self.conn.send (data, pos) pos += n if not more: break else: pass left -= n return pos def shutdown (self, how=None): more = 1 while more: more = self.conn.shutdown() def close (self): try: self.shutdown() finally: self.sock.close()
negotiate
identifier_name
__init__.py
# -*- Mode: Python -*- import socket import unittest __version__ = '0.1.1' from .cys2n import * protocol_version_map = { 'SSLv2' : 20, 'SSLv3' : 30, 'TLS10' : 31, 'TLS11' : 32, 'TLS12' : 33, } class PROTOCOL: reverse_map = {} for name, val in protocol_version_map.items(): setattr (PROTOCOL, name, val) PROTOCOL.reverse_map[val] = name class s2n_socket: def __init__ (self, cfg, pysock, conn=None): self.cfg = cfg self.sock = pysock self.fd = pysock.fileno() self.conn = conn self.negotiated = False def __repr__ (self): return '<s2n sock=%r conn=%r @%x>' % (self.sock, self.conn, id (self)) def bind (self, *args, **kwargs): return self.sock.bind (*args, **kwargs) def listen (self, *args, **kwargs): return self.sock.listen (*args, **kwargs) def accept (self): sock, addr = self.sock.accept() conn = Connection (MODE.SERVER) conn.set_config (self.cfg) conn.set_fd (sock.fileno()) # XXX verify new = self.__class__ (self.cfg, sock, conn) return new, addr # XXX client mode as yet untested. def connect (self, addr): self.sock.connect (addr) self.conn = Connection (MODE.CLIENT) self.conn.set_config (self.cfg) self.conn.set_fd (self.fd) def _check_negotiated (self): if not self.negotiated: self.negotiate() def negotiate (self): if not self.negotiated: self.conn.negotiate() self.negotiated = True def recv (self, block_size): self._check_negotiated() r = [] left = block_size while left: b, more = self.conn.recv (left) r.append (b) if not more: break else: left -= len(b) return b''.join (r) def send (self, data): self._check_negotiated() pos = 0 left = len(data) while left: n, more = self.conn.send (data, pos) pos += n if not more:
else: pass left -= n return pos def shutdown (self, how=None): more = 1 while more: more = self.conn.shutdown() def close (self): try: self.shutdown() finally: self.sock.close()
break
conditional_block
ek-instance-filters.controller.js
/* Copyright 2016 ElasticBox 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. */ class InstanceFiltersController { constructor($scope) { 'ngInject'; this.instancesFilteredByState = []; this.selectedOwners = []; this.filteredInstances = []; $scope.$watch('ctrl.selectedState', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.instancesToFilter', () => this.filterInstancesByState());
this.instancesFilteredByState = _.chain(this.instancesToFilter) .filter((x) => { return _.isUndefined(this.selectedState) || this.selectedState.state.kind === 'all' || this.selectedState.state.kind.toLowerCase() === (x.kind || '').toLowerCase() && _.isUndefined(this.selectedState.substate) || !_.isUndefined(this.selectedState.substate) && _.get(x, 'status.phase') === this.selectedState.substate.state; }) .value(); } filterInstancesByOwners() { this.filteredInstances = _.isEmpty(this.selectedOwners) ? this.instancesFilteredByState : _.filter(this.instancesFilteredByState, (x) => _.includes(this.selectedOwners, x.owner)); } } export default InstanceFiltersController;
$scope.$watchCollection('ctrl.selectedOwners', () => this.filterInstancesByOwners()); $scope.$watchCollection('ctrl.instancesFilteredByState', () => this.filterInstancesByOwners()); } filterInstancesByState() {
random_line_split
ek-instance-filters.controller.js
/* Copyright 2016 ElasticBox 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. */ class InstanceFiltersController { constructor($scope) { 'ngInject'; this.instancesFilteredByState = []; this.selectedOwners = []; this.filteredInstances = []; $scope.$watch('ctrl.selectedState', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.instancesToFilter', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.selectedOwners', () => this.filterInstancesByOwners()); $scope.$watchCollection('ctrl.instancesFilteredByState', () => this.filterInstancesByOwners()); } filterInstancesByState() { this.instancesFilteredByState = _.chain(this.instancesToFilter) .filter((x) => { return _.isUndefined(this.selectedState) || this.selectedState.state.kind === 'all' || this.selectedState.state.kind.toLowerCase() === (x.kind || '').toLowerCase() && _.isUndefined(this.selectedState.substate) || !_.isUndefined(this.selectedState.substate) && _.get(x, 'status.phase') === this.selectedState.substate.state; }) .value(); } filterInstancesByOwners()
} export default InstanceFiltersController;
{ this.filteredInstances = _.isEmpty(this.selectedOwners) ? this.instancesFilteredByState : _.filter(this.instancesFilteredByState, (x) => _.includes(this.selectedOwners, x.owner)); }
identifier_body
ek-instance-filters.controller.js
/* Copyright 2016 ElasticBox 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. */ class InstanceFiltersController { constructor($scope) { 'ngInject'; this.instancesFilteredByState = []; this.selectedOwners = []; this.filteredInstances = []; $scope.$watch('ctrl.selectedState', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.instancesToFilter', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.selectedOwners', () => this.filterInstancesByOwners()); $scope.$watchCollection('ctrl.instancesFilteredByState', () => this.filterInstancesByOwners()); }
() { this.instancesFilteredByState = _.chain(this.instancesToFilter) .filter((x) => { return _.isUndefined(this.selectedState) || this.selectedState.state.kind === 'all' || this.selectedState.state.kind.toLowerCase() === (x.kind || '').toLowerCase() && _.isUndefined(this.selectedState.substate) || !_.isUndefined(this.selectedState.substate) && _.get(x, 'status.phase') === this.selectedState.substate.state; }) .value(); } filterInstancesByOwners() { this.filteredInstances = _.isEmpty(this.selectedOwners) ? this.instancesFilteredByState : _.filter(this.instancesFilteredByState, (x) => _.includes(this.selectedOwners, x.owner)); } } export default InstanceFiltersController;
filterInstancesByState
identifier_name
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods; use dom::bindings::codegen::InheritTypes::HTMLObjectElementDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{Element, HTMLObjectElementTypeId}; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_net::image_cache_task; use servo_net::image_cache_task::ImageCacheTask; use servo_util::str::DOMString; use string_cache::Atom; use url::Url; #[dom_struct] pub struct HTMLObjectElement { htmlelement: HTMLElement, } impl HTMLObjectElementDerived for EventTarget { fn is_htmlobjectelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLObjectElementTypeId)) } } impl HTMLObjectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLObjectElement { HTMLObjectElement { htmlelement: HTMLElement::new_inherited(HTMLObjectElementTypeId, localName, prefix, document), } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLObjectElement> { let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) } } trait ProcessDataURL { fn process_data_url(&self, image_cache: ImageCacheTask); } impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> { // Makes the local `data` member match the status of the `data` attribute and starts /// prefetching the image. This method must be called after `data` is changed. fn process_data_url(&self, image_cache: ImageCacheTask)
} pub fn is_image_data(uri: &str) -> bool { static types: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) } impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(*window) } // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_getter!(Type) // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_setter!(SetType, "type") } impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("data") => { let window = window_from_node(*self).root(); self.process_data_url(window.image_cache_task().clone()); }, _ => () } } } impl Reflectable for HTMLObjectElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ let elem: JSRef<Element> = ElementCast::from_ref(*self); // TODO: support other values match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().Value()), elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().Value())) { (None, Some(uri)) => { if is_image_data(uri.as_slice()) { let data_url = Url::parse(uri.as_slice()).unwrap(); // Issue #84 image_cache.send(image_cache_task::Prefetch(data_url)); } } _ => { } } }
identifier_body
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods; use dom::bindings::codegen::InheritTypes::HTMLObjectElementDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{Element, HTMLObjectElementTypeId}; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_net::image_cache_task; use servo_net::image_cache_task::ImageCacheTask; use servo_util::str::DOMString; use string_cache::Atom; use url::Url; #[dom_struct] pub struct HTMLObjectElement { htmlelement: HTMLElement, } impl HTMLObjectElementDerived for EventTarget { fn is_htmlobjectelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLObjectElementTypeId)) } } impl HTMLObjectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLObjectElement { HTMLObjectElement { htmlelement: HTMLElement::new_inherited(HTMLObjectElementTypeId, localName, prefix, document), } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLObjectElement> { let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) } } trait ProcessDataURL { fn process_data_url(&self, image_cache: ImageCacheTask); } impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> { // Makes the local `data` member match the status of the `data` attribute and starts /// prefetching the image. This method must be called after `data` is changed. fn process_data_url(&self, image_cache: ImageCacheTask) { let elem: JSRef<Element> = ElementCast::from_ref(*self); // TODO: support other values match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().Value()), elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().Value())) { (None, Some(uri)) => { if is_image_data(uri.as_slice()) { let data_url = Url::parse(uri.as_slice()).unwrap(); // Issue #84 image_cache.send(image_cache_task::Prefetch(data_url)); } } _ => { } } } } pub fn
(uri: &str) -> bool { static types: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) } impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(*window) } // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_getter!(Type) // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_setter!(SetType, "type") } impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("data") => { let window = window_from_node(*self).root(); self.process_data_url(window.image_cache_task().clone()); }, _ => () } } } impl Reflectable for HTMLObjectElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
is_image_data
identifier_name
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods; use dom::bindings::codegen::InheritTypes::HTMLObjectElementDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{Element, HTMLObjectElementTypeId}; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_net::image_cache_task; use servo_net::image_cache_task::ImageCacheTask; use servo_util::str::DOMString; use string_cache::Atom; use url::Url; #[dom_struct] pub struct HTMLObjectElement { htmlelement: HTMLElement, } impl HTMLObjectElementDerived for EventTarget { fn is_htmlobjectelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLObjectElementTypeId)) } } impl HTMLObjectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLObjectElement { HTMLObjectElement { htmlelement: HTMLElement::new_inherited(HTMLObjectElementTypeId, localName, prefix, document), } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLObjectElement> { let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) } } trait ProcessDataURL { fn process_data_url(&self, image_cache: ImageCacheTask); } impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> { // Makes the local `data` member match the status of the `data` attribute and starts /// prefetching the image. This method must be called after `data` is changed. fn process_data_url(&self, image_cache: ImageCacheTask) { let elem: JSRef<Element> = ElementCast::from_ref(*self); // TODO: support other values match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().Value()), elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().Value())) { (None, Some(uri)) => { if is_image_data(uri.as_slice()) { let data_url = Url::parse(uri.as_slice()).unwrap(); // Issue #84 image_cache.send(image_cache_task::Prefetch(data_url)); } } _ => { } } } } pub fn is_image_data(uri: &str) -> bool { static types: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) } impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(*window) }
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_setter!(SetType, "type") } impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("data") => { let window = window_from_node(*self).root(); self.process_data_url(window.image_cache_task().clone()); }, _ => () } } } impl Reflectable for HTMLObjectElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_getter!(Type)
random_line_split
youtube-service.ts
import { Http, URLSearchParams, Response } from '@angular/http'; import { Injectable, NgZone } from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser'; @Injectable() export class YoutubeService { youtube: any = { ready: false, player: null, playerId: null, videoId: null, videoTitle: null, playerHeight: '100%', playerWidth: '100%' } constructor () { this.setupPlayer(); } bindPlayer(elementId): void { this.youtube.playerId = elementId; };
(): void { console.log ("create player after ready"); return new window.YT.Player(this.youtube.playerId, { height: this.youtube.playerHeight, width: this.youtube.playerWidth, playerVars: { rel: 0, showinfo: 0 } }); } loadPlayer(): void { if (this.youtube.ready && this.youtube.playerId) { console.log ("loadPlayer player id is ready"); if (this.youtube.player) { this.youtube.player.destroy(); } this.youtube.player = this.createPlayer(); } } setupPlayer () { // in production mode, the youtube iframe api script tag is loaded // before the bundle.js, so the 'onYouTubeIfarmeAPIReady' has // already been triggered // TODO: handle this in build or in nicer in code console.log ("Running Setup Player"); window['onYouTubeIframeAPIReady'] = () => { if (window['YT']) { console.log('Youtube API is ready'); this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } }; if (window.YT && window.YT.Player) { this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } } launchPlayer(id, title):void { this.youtube.player.loadVideoById(id); this.youtube.videoId = id; this.youtube.videoTitle = title; return this.youtube; } }
createPlayer
identifier_name
youtube-service.ts
import { Http, URLSearchParams, Response } from '@angular/http'; import { Injectable, NgZone } from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser';
playerId: null, videoId: null, videoTitle: null, playerHeight: '100%', playerWidth: '100%' } constructor () { this.setupPlayer(); } bindPlayer(elementId): void { this.youtube.playerId = elementId; }; createPlayer(): void { console.log ("create player after ready"); return new window.YT.Player(this.youtube.playerId, { height: this.youtube.playerHeight, width: this.youtube.playerWidth, playerVars: { rel: 0, showinfo: 0 } }); } loadPlayer(): void { if (this.youtube.ready && this.youtube.playerId) { console.log ("loadPlayer player id is ready"); if (this.youtube.player) { this.youtube.player.destroy(); } this.youtube.player = this.createPlayer(); } } setupPlayer () { // in production mode, the youtube iframe api script tag is loaded // before the bundle.js, so the 'onYouTubeIfarmeAPIReady' has // already been triggered // TODO: handle this in build or in nicer in code console.log ("Running Setup Player"); window['onYouTubeIframeAPIReady'] = () => { if (window['YT']) { console.log('Youtube API is ready'); this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } }; if (window.YT && window.YT.Player) { this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } } launchPlayer(id, title):void { this.youtube.player.loadVideoById(id); this.youtube.videoId = id; this.youtube.videoTitle = title; return this.youtube; } }
@Injectable() export class YoutubeService { youtube: any = { ready: false, player: null,
random_line_split
youtube-service.ts
import { Http, URLSearchParams, Response } from '@angular/http'; import { Injectable, NgZone } from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser'; @Injectable() export class YoutubeService { youtube: any = { ready: false, player: null, playerId: null, videoId: null, videoTitle: null, playerHeight: '100%', playerWidth: '100%' } constructor () { this.setupPlayer(); } bindPlayer(elementId): void { this.youtube.playerId = elementId; }; createPlayer(): void { console.log ("create player after ready"); return new window.YT.Player(this.youtube.playerId, { height: this.youtube.playerHeight, width: this.youtube.playerWidth, playerVars: { rel: 0, showinfo: 0 } }); } loadPlayer(): void { if (this.youtube.ready && this.youtube.playerId) { console.log ("loadPlayer player id is ready"); if (this.youtube.player)
this.youtube.player = this.createPlayer(); } } setupPlayer () { // in production mode, the youtube iframe api script tag is loaded // before the bundle.js, so the 'onYouTubeIfarmeAPIReady' has // already been triggered // TODO: handle this in build or in nicer in code console.log ("Running Setup Player"); window['onYouTubeIframeAPIReady'] = () => { if (window['YT']) { console.log('Youtube API is ready'); this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } }; if (window.YT && window.YT.Player) { this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } } launchPlayer(id, title):void { this.youtube.player.loadVideoById(id); this.youtube.videoId = id; this.youtube.videoTitle = title; return this.youtube; } }
{ this.youtube.player.destroy(); }
conditional_block
youtube-service.ts
import { Http, URLSearchParams, Response } from '@angular/http'; import { Injectable, NgZone } from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser'; @Injectable() export class YoutubeService { youtube: any = { ready: false, player: null, playerId: null, videoId: null, videoTitle: null, playerHeight: '100%', playerWidth: '100%' } constructor () { this.setupPlayer(); } bindPlayer(elementId): void
; createPlayer(): void { console.log ("create player after ready"); return new window.YT.Player(this.youtube.playerId, { height: this.youtube.playerHeight, width: this.youtube.playerWidth, playerVars: { rel: 0, showinfo: 0 } }); } loadPlayer(): void { if (this.youtube.ready && this.youtube.playerId) { console.log ("loadPlayer player id is ready"); if (this.youtube.player) { this.youtube.player.destroy(); } this.youtube.player = this.createPlayer(); } } setupPlayer () { // in production mode, the youtube iframe api script tag is loaded // before the bundle.js, so the 'onYouTubeIfarmeAPIReady' has // already been triggered // TODO: handle this in build or in nicer in code console.log ("Running Setup Player"); window['onYouTubeIframeAPIReady'] = () => { if (window['YT']) { console.log('Youtube API is ready'); this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } }; if (window.YT && window.YT.Player) { this.youtube.ready = true; this.bindPlayer('placeholder'); this.loadPlayer(); } } launchPlayer(id, title):void { this.youtube.player.loadVideoById(id); this.youtube.videoId = id; this.youtube.videoTitle = title; return this.youtube; } }
{ this.youtube.playerId = elementId; }
identifier_body
cecog.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def merge(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService()
fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:])
# if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path):
random_line_split
cecog.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def
(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:])
merge
identifier_name
cecog.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl):
try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:])
"""CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def merge(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath): subDirs.append(fullpath) # get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids))
identifier_body
cecog.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.constants from omero.rtypes import rstring class CecogControl(BaseControl): """CeCog integration plugin. Provides actions for prepairing data and otherwise integrating with Cecog. See the Run_Cecog_4.1.py script. """ # [MetaMorph_PlateScanPackage] # regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?') # regex_position = re.compile('P(?P<P>.+?)_') # continuous_frames = 1 regex_token = re.compile(r'(?P<Token>.+)\.') regex_time = re.compile(r'T(?P<T>\d+)') regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)') regex_zslice = re.compile(r'_Z(?P<Z>\d+)') def _configure(self, parser): sub = parser.sub() merge = parser.add(sub, self.merge, self.merge.__doc__) merge.add_argument("path", help="Path to image files") rois = parser.add(sub, self.rois, self.rois.__doc__) rois.add_argument( "-f", "--file", required=True, help="Details file to be parsed") rois.add_argument( "-i", "--image", required=True, help="Image id which should have ids attached") for x in (merge, rois): x.add_login_arguments() # # Public methods # def merge(self, args): """Uses PIL to read multiple planes from a local folder. Planes are combined and uploaded to OMERO as new images with additional T, C, Z dimensions. It should be run as a local script (not via scripting service) in order that it has access to the local users file system. Therefore need EMAN2 or PIL installed locally. Example usage: $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/ Since this dir does not contain folders, this will upload images in '0037' into a Dataset called Demo_data in a Project called 'Data'. $ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/ Since this dir does contain folders, this will look for images in all subdirectories of 'Demo_data' and upload images into a Dataset called Demo_data in a Project called 'Data'. Images will be combined in Z, C and T according to the \ MetaMorph_PlateScanPackage naming convention. E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \ gfp, Z 1. S? see \ /Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\ naming_schemes.conf """ """ Processes the command args, makes project and dataset then calls uploadDirAsImages() to process and upload the images to OMERO. """ from omero.rtypes import unwrap from omero.util.script_utils import uploadDirAsImages path = args.path client = self.ctx.conn(args) queryService = client.sf.getQueryService() updateService = client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f # process folders in root dir: if os.path.isdir(fullpath):
# get the dataset name and project name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p = p[:-1] p = os.path.dirname(p) projectName = os.path.basename(p) # e.g. Data self.ctx.err("Putting images in Project: %s Dataset: %s" % (projectName, datasetName)) # create dataset dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) dataset = updateService.saveAndReturnObject(dataset) # create project project = omero.model.ProjectI() project.name = rstring(projectName) project = updateService.saveAndReturnObject(project) # put dataset in project link = omero.model.ProjectDatasetLinkI() link.parent = omero.model.ProjectI(project.id.val, False) link.child = omero.model.DatasetI(dataset.id.val, False) updateService.saveAndReturnObject(link) if len(subDirs) > 0: for subDir in subDirs: self.ctx.err("Processing images in %s" % subDir) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, subDir, dataset) self.ctx.out("%s" % unwrap(rv)) # if there are no sub-directories, just put all the images in the dir else: self.ctx.err("Processing images in %s" % path) rv = uploadDirAsImages(client.sf, queryService, updateService, pixelsService, path, dataset) self.ctx.out("%s" % unwrap(rv)) def rois(self, args): """Parses an object_details text file, as generated by CeCog Analyzer and saves the data as ROIs on an Image in OMERO. Text file is of the form: frame objID classLabel className centerX centerY mean sd 1 10 6 lateana 1119 41 76.8253796095 \ 54.9305640673 Example usage: bin/omero cecog rois -f \ Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502 """ """ Processes the command args, parses the object_details.txt file and creates ROIs on the image specified in OMERO """ from omero.util.script_utils import uploadCecogObjectDetails filePath = args.file imageId = args.image if not os.path.exists(filePath): self.ctx.die(654, "Could find the object_details file at %s" % filePath) client = self.ctx.conn(args) updateService = client.sf.getUpdateService() ids = uploadCecogObjectDetails(updateService, imageId, filePath) self.ctx.out("Rois created: %s" % len(ids)) try: register("cecog", CecogControl, CecogControl.__doc__) except NameError: if __name__ == "__main__": cli = CLI() cli.register("cecog", CecogControl, CecogControl.__doc__) cli.invoke(sys.argv[1:])
subDirs.append(fullpath)
conditional_block
settings.py
""" Django settings for ltc_huobi project. Generated by 'django-admin startproject' using Django 1.11.2. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import ltc # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6t$e^bg18g6u)((0gvfb(dnfh5y&=0_lz&5*-6hrs=mc&u1j#t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ltc_huobi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ltc_huobi.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/'
'ltc.apps.LtcConfig',
random_line_split
stepper-demo.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, OnInit} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'stepper-demo', templateUrl: 'stepper-demo.html', }) export class StepperDemo implements OnInit { formGroup: FormGroup; isNonLinear = false; isNonEditable = false; disableRipple = false; showLabelBottom = false; isVertical = false; nameFormGroup: FormGroup; emailFormGroup: FormGroup; steps = [ {label: 'Confirm your name', content: 'Last name, First name.'}, {label: 'Confirm your contact information', content: '123-456-7890'}, {label: 'Confirm your address', content: '1600 Amphitheater Pkwy MTV'}, {label: 'You are now done', content: 'Finished!'}, ]; availableThemes: {value: ThemePalette; name: string}[] = [ {value: 'primary', name: 'Primary'}, {value: 'accent', name: 'Accent'}, {value: 'warn', name: 'Warn'}, ]; theme = this.availableThemes[0].value; /** Returns a FormArray with the name 'formArray'. */ get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); } constructor(private _formBuilder: FormBuilder)
ngOnInit() { this.formGroup = this._formBuilder.group({ formArray: this._formBuilder.array([ this._formBuilder.group({ firstNameFormCtrl: ['', Validators.required], lastNameFormCtrl: ['', Validators.required], }), this._formBuilder.group({ emailFormCtrl: ['', Validators.email], }), ]), }); this.nameFormGroup = this._formBuilder.group({ firstNameCtrl: ['', Validators.required], lastNameCtrl: ['', Validators.required], }); this.emailFormGroup = this._formBuilder.group({ emailCtrl: ['', Validators.email], }); } }
{}
identifier_body
stepper-demo.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, OnInit} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'stepper-demo', templateUrl: 'stepper-demo.html', }) export class StepperDemo implements OnInit { formGroup: FormGroup; isNonLinear = false; isNonEditable = false; disableRipple = false; showLabelBottom = false; isVertical = false; nameFormGroup: FormGroup; emailFormGroup: FormGroup; steps = [ {label: 'Confirm your name', content: 'Last name, First name.'}, {label: 'Confirm your contact information', content: '123-456-7890'}, {label: 'Confirm your address', content: '1600 Amphitheater Pkwy MTV'}, {label: 'You are now done', content: 'Finished!'}, ]; availableThemes: {value: ThemePalette; name: string}[] = [ {value: 'primary', name: 'Primary'}, {value: 'accent', name: 'Accent'}, {value: 'warn', name: 'Warn'},
theme = this.availableThemes[0].value; /** Returns a FormArray with the name 'formArray'. */ get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); } constructor(private _formBuilder: FormBuilder) {} ngOnInit() { this.formGroup = this._formBuilder.group({ formArray: this._formBuilder.array([ this._formBuilder.group({ firstNameFormCtrl: ['', Validators.required], lastNameFormCtrl: ['', Validators.required], }), this._formBuilder.group({ emailFormCtrl: ['', Validators.email], }), ]), }); this.nameFormGroup = this._formBuilder.group({ firstNameCtrl: ['', Validators.required], lastNameCtrl: ['', Validators.required], }); this.emailFormGroup = this._formBuilder.group({ emailCtrl: ['', Validators.email], }); } }
];
random_line_split
stepper-demo.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, OnInit} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'stepper-demo', templateUrl: 'stepper-demo.html', }) export class
implements OnInit { formGroup: FormGroup; isNonLinear = false; isNonEditable = false; disableRipple = false; showLabelBottom = false; isVertical = false; nameFormGroup: FormGroup; emailFormGroup: FormGroup; steps = [ {label: 'Confirm your name', content: 'Last name, First name.'}, {label: 'Confirm your contact information', content: '123-456-7890'}, {label: 'Confirm your address', content: '1600 Amphitheater Pkwy MTV'}, {label: 'You are now done', content: 'Finished!'}, ]; availableThemes: {value: ThemePalette; name: string}[] = [ {value: 'primary', name: 'Primary'}, {value: 'accent', name: 'Accent'}, {value: 'warn', name: 'Warn'}, ]; theme = this.availableThemes[0].value; /** Returns a FormArray with the name 'formArray'. */ get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); } constructor(private _formBuilder: FormBuilder) {} ngOnInit() { this.formGroup = this._formBuilder.group({ formArray: this._formBuilder.array([ this._formBuilder.group({ firstNameFormCtrl: ['', Validators.required], lastNameFormCtrl: ['', Validators.required], }), this._formBuilder.group({ emailFormCtrl: ['', Validators.email], }), ]), }); this.nameFormGroup = this._formBuilder.group({ firstNameCtrl: ['', Validators.required], lastNameCtrl: ['', Validators.required], }); this.emailFormGroup = this._formBuilder.group({ emailCtrl: ['', Validators.email], }); } }
StepperDemo
identifier_name
environment_variable_config_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 {EnvironmentVariableConfig} from "models/new_pipeline_configs/environment_variable_config"; describe("EnvironmentVariableConfig model", () => { function validEnvironmentVariableConfig() { return new EnvironmentVariableConfig(false, "KEY", "value"); } function
() { return new EnvironmentVariableConfig(true, "KEY", "value"); } it("should validate presence of name", () => { let envVar = validEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); validSecureEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); envVar = new EnvironmentVariableConfig(false, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); envVar = new EnvironmentVariableConfig(true, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); }); it("adopts errors in server response", () => { const env = validEnvironmentVariableConfig(); const unmatched = env.consumeErrorsResponse({ errors: { name: ["this name is uncreative"], not_exist: ["well, ain't that a doozy"] } }); expect(env.errors().errorsForDisplay("name")).toBe("this name is uncreative."); expect(unmatched.hasErrors()).toBe(true); expect(unmatched.errorsForDisplay("environmentVariableConfig.notExist")).toBe("well, ain't that a doozy."); }); it("should serialize correctly", () => { const envVar = validEnvironmentVariableConfig(); expect(envVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: false }); const secureVar = validSecureEnvironmentVariableConfig(); expect(secureVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: true }); }); });
validSecureEnvironmentVariableConfig
identifier_name
environment_variable_config_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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
import {EnvironmentVariableConfig} from "models/new_pipeline_configs/environment_variable_config"; describe("EnvironmentVariableConfig model", () => { function validEnvironmentVariableConfig() { return new EnvironmentVariableConfig(false, "KEY", "value"); } function validSecureEnvironmentVariableConfig() { return new EnvironmentVariableConfig(true, "KEY", "value"); } it("should validate presence of name", () => { let envVar = validEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); validSecureEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); envVar = new EnvironmentVariableConfig(false, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); envVar = new EnvironmentVariableConfig(true, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); }); it("adopts errors in server response", () => { const env = validEnvironmentVariableConfig(); const unmatched = env.consumeErrorsResponse({ errors: { name: ["this name is uncreative"], not_exist: ["well, ain't that a doozy"] } }); expect(env.errors().errorsForDisplay("name")).toBe("this name is uncreative."); expect(unmatched.hasErrors()).toBe(true); expect(unmatched.errorsForDisplay("environmentVariableConfig.notExist")).toBe("well, ain't that a doozy."); }); it("should serialize correctly", () => { const envVar = validEnvironmentVariableConfig(); expect(envVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: false }); const secureVar = validSecureEnvironmentVariableConfig(); expect(secureVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: true }); }); });
* limitations under the License. */
random_line_split
environment_variable_config_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 {EnvironmentVariableConfig} from "models/new_pipeline_configs/environment_variable_config"; describe("EnvironmentVariableConfig model", () => { function validEnvironmentVariableConfig()
function validSecureEnvironmentVariableConfig() { return new EnvironmentVariableConfig(true, "KEY", "value"); } it("should validate presence of name", () => { let envVar = validEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); validSecureEnvironmentVariableConfig(); expect(envVar.isValid()).toBe(true); expect(envVar.errors().count()).toBe(0); envVar = new EnvironmentVariableConfig(false, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); envVar = new EnvironmentVariableConfig(true, "", ""); expect(envVar.isValid()).toBe(false); expect(envVar.errors().count()).toBe(1); }); it("adopts errors in server response", () => { const env = validEnvironmentVariableConfig(); const unmatched = env.consumeErrorsResponse({ errors: { name: ["this name is uncreative"], not_exist: ["well, ain't that a doozy"] } }); expect(env.errors().errorsForDisplay("name")).toBe("this name is uncreative."); expect(unmatched.hasErrors()).toBe(true); expect(unmatched.errorsForDisplay("environmentVariableConfig.notExist")).toBe("well, ain't that a doozy."); }); it("should serialize correctly", () => { const envVar = validEnvironmentVariableConfig(); expect(envVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: false }); const secureVar = validSecureEnvironmentVariableConfig(); expect(secureVar.toApiPayload()).toEqual({ name: "KEY", value: "value", secure: true }); }); });
{ return new EnvironmentVariableConfig(false, "KEY", "value"); }
identifier_body
VideoTexture.d.ts
import { Texture } from './Texture'; import { Mapping, Wrapping, TextureFilter, PixelFormat, TextureDataType } from '../constants'; export class VideoTexture extends Texture { /** * @param video * @param [mapping=THREE.Texture.DEFAULT_MAPPING] * @param [wrapS=THREE.ClampToEdgeWrapping] * @param [wrapT=THREE.ClampToEdgeWrapping] * @param [magFilter=THREE.LinearFilter] * @param [minFilter=THREE.LinearFilter] * @param [format=THREE.RGBFormat] * @param [type=THREE.UnsignedByteType]
constructor( video: HTMLVideoElement, mapping?: Mapping, wrapS?: Wrapping, wrapT?: Wrapping, magFilter?: TextureFilter, minFilter?: TextureFilter, format?: PixelFormat, type?: TextureDataType, anisotropy?: number, ); readonly isVideoTexture: true; /** * @default false */ generateMipmaps: boolean; }
* @param [anisotropy=1] */
random_line_split
VideoTexture.d.ts
import { Texture } from './Texture'; import { Mapping, Wrapping, TextureFilter, PixelFormat, TextureDataType } from '../constants'; export class
extends Texture { /** * @param video * @param [mapping=THREE.Texture.DEFAULT_MAPPING] * @param [wrapS=THREE.ClampToEdgeWrapping] * @param [wrapT=THREE.ClampToEdgeWrapping] * @param [magFilter=THREE.LinearFilter] * @param [minFilter=THREE.LinearFilter] * @param [format=THREE.RGBFormat] * @param [type=THREE.UnsignedByteType] * @param [anisotropy=1] */ constructor( video: HTMLVideoElement, mapping?: Mapping, wrapS?: Wrapping, wrapT?: Wrapping, magFilter?: TextureFilter, minFilter?: TextureFilter, format?: PixelFormat, type?: TextureDataType, anisotropy?: number, ); readonly isVideoTexture: true; /** * @default false */ generateMipmaps: boolean; }
VideoTexture
identifier_name
views.py
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from allauth.socialaccount import requests from allauth.socialaccount.models import SocialLogin, SocialAccount from allauth.utils import get_user_model from provider import GoogleProvider User = get_user_model() class GoogleOAuth2Adapter(OAuth2Adapter): provider_id = GoogleProvider.id access_token_url = 'https://accounts.google.com/o/oauth2/token' authorize_url = 'https://accounts.google.com/o/oauth2/auth' profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo' def
(self, request, app, token): resp = requests.get(self.profile_url, { 'access_token': token.token, 'alt': 'json' }) extra_data = resp.json # extra_data is something of the form: # # {u'family_name': u'Penners', u'name': u'Raymond Penners', # u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg', # u'locale': u'nl', u'gender': u'male', # u'email': u'[email protected]', # u'link': u'https://plus.google.com/108204268033311374519', # u'given_name': u'Raymond', u'id': u'108204268033311374519', # u'verified_email': True} # # TODO: We could use verified_email to bypass allauth email verification uid = str(extra_data['id']) user = User(email=extra_data.get('email', ''), last_name=extra_data.get('family_name', ''), first_name=extra_data.get('given_name', '')) account = SocialAccount(extra_data=extra_data, uid=uid, provider=self.provider_id, user=user) return SocialLogin(account) oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
complete_login
identifier_name
views.py
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from allauth.socialaccount import requests from allauth.socialaccount.models import SocialLogin, SocialAccount from allauth.utils import get_user_model from provider import GoogleProvider User = get_user_model() class GoogleOAuth2Adapter(OAuth2Adapter):
oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
provider_id = GoogleProvider.id access_token_url = 'https://accounts.google.com/o/oauth2/token' authorize_url = 'https://accounts.google.com/o/oauth2/auth' profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo' def complete_login(self, request, app, token): resp = requests.get(self.profile_url, { 'access_token': token.token, 'alt': 'json' }) extra_data = resp.json # extra_data is something of the form: # # {u'family_name': u'Penners', u'name': u'Raymond Penners', # u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg', # u'locale': u'nl', u'gender': u'male', # u'email': u'[email protected]', # u'link': u'https://plus.google.com/108204268033311374519', # u'given_name': u'Raymond', u'id': u'108204268033311374519', # u'verified_email': True} # # TODO: We could use verified_email to bypass allauth email verification uid = str(extra_data['id']) user = User(email=extra_data.get('email', ''), last_name=extra_data.get('family_name', ''), first_name=extra_data.get('given_name', '')) account = SocialAccount(extra_data=extra_data, uid=uid, provider=self.provider_id, user=user) return SocialLogin(account)
identifier_body
views.py
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from allauth.socialaccount import requests from allauth.socialaccount.models import SocialLogin, SocialAccount from allauth.utils import get_user_model from provider import GoogleProvider User = get_user_model() class GoogleOAuth2Adapter(OAuth2Adapter): provider_id = GoogleProvider.id access_token_url = 'https://accounts.google.com/o/oauth2/token' authorize_url = 'https://accounts.google.com/o/oauth2/auth' profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo' def complete_login(self, request, app, token): resp = requests.get(self.profile_url, { 'access_token': token.token, 'alt': 'json' }) extra_data = resp.json # extra_data is something of the form: # # {u'family_name': u'Penners', u'name': u'Raymond Penners', # u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg', # u'locale': u'nl', u'gender': u'male', # u'email': u'[email protected]', # u'link': u'https://plus.google.com/108204268033311374519', # u'given_name': u'Raymond', u'id': u'108204268033311374519', # u'verified_email': True} # # TODO: We could use verified_email to bypass allauth email verification uid = str(extra_data['id']) user = User(email=extra_data.get('email', ''), last_name=extra_data.get('family_name', ''), first_name=extra_data.get('given_name', '')) account = SocialAccount(extra_data=extra_data,
uid=uid, provider=self.provider_id, user=user) return SocialLogin(account) oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
random_line_split
local.js
var TemplateLibraryTemplateView = require( 'elementor-templates/views/template/base' ), TemplateLibraryTemplateLocalView; TemplateLibraryTemplateLocalView = TemplateLibraryTemplateView.extend( { template: '#tmpl-elementor-template-library-template-local', ui: function() { return _.extend( TemplateLibraryTemplateView.prototype.ui.apply( this, arguments ), { deleteButton: '.elementor-template-library-template-delete', morePopup: '.elementor-template-library-template-more', toggleMore: '.elementor-template-library-template-more-toggle', toggleMoreIcon: '.elementor-template-library-template-more-toggle i', } ); },
'click @ui.toggleMore': 'onToggleMoreClick', } ); }, onDeleteButtonClick: function() { var toggleMoreIcon = this.ui.toggleMoreIcon; elementor.templates.deleteTemplate( this.model, { onConfirm: function() { toggleMoreIcon.removeClass( 'eicon-ellipsis-h' ).addClass( 'eicon-loading eicon-animation-spin' ); }, onSuccess: function() { elementor.templates.showTemplates(); }, } ); }, onToggleMoreClick: function() { this.ui.morePopup.show(); }, onPreviewButtonClick: function() { open( this.model.get( 'url' ), '_blank' ); }, } ); module.exports = TemplateLibraryTemplateLocalView;
events: function() { return _.extend( TemplateLibraryTemplateView.prototype.events.apply( this, arguments ), { 'click @ui.deleteButton': 'onDeleteButtonClick',
random_line_split
addn_packed_gpu.ts
/** * @license * Copyright 2019 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {GPGPUProgram} from './gpgpu_math'; export class AddNPackedProgram implements GPGPUProgram { variableNames: string[]; outputShape: number[] = []; userCode: string; usesPackedTextures = true; constructor(outputShape: number[], shapes: number[][]) { this.outputShape = outputShape; this.variableNames = shapes.map((_, i) => `T${i}`); const snippets: string[] = []; // Get target elements from every input tensor. this.variableNames.forEach(variable => { snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`); }); // Calculate the sum of all elements. const operation = this.variableNames .map(variable => { return `v${variable}`; }) .join(' + ');
this.userCode = ` void main() { ${snippets.join('\n ')} vec4 result = ${operation}; setOutput(result); } `; } }
random_line_split
addn_packed_gpu.ts
/** * @license * Copyright 2019 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {GPGPUProgram} from './gpgpu_math'; export class AddNPackedProgram implements GPGPUProgram { variableNames: string[]; outputShape: number[] = []; userCode: string; usesPackedTextures = true;
(outputShape: number[], shapes: number[][]) { this.outputShape = outputShape; this.variableNames = shapes.map((_, i) => `T${i}`); const snippets: string[] = []; // Get target elements from every input tensor. this.variableNames.forEach(variable => { snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`); }); // Calculate the sum of all elements. const operation = this.variableNames .map(variable => { return `v${variable}`; }) .join(' + '); this.userCode = ` void main() { ${snippets.join('\n ')} vec4 result = ${operation}; setOutput(result); } `; } }
constructor
identifier_name
performance.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::performancetiming::{PerformanceTiming, PerformanceTimingMethods}; use dom::window::Window; use time; pub type DOMHighResTimeStamp = f64; #[deriving(Encodable)] pub struct Performance { reflector_: Reflector, timing: JS<PerformanceTiming>, } impl Performance { fn new_inherited(window: &JSRef<Window>) -> Performance
pub fn new(window: &JSRef<Window>) -> Temporary<Performance> { let performance = Performance::new_inherited(window); reflect_dom_object(box performance, window, PerformanceBinding::Wrap) } } pub trait PerformanceMethods { fn Timing(&self) -> Temporary<PerformanceTiming>; fn Now(&self) -> DOMHighResTimeStamp; } impl<'a> PerformanceMethods for JSRef<'a, Performance> { fn Timing(&self) -> Temporary<PerformanceTiming> { Temporary::new(self.timing.clone()) } fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().NavigationStartPrecise() as f64; (time::precise_time_s() - navStart) as DOMHighResTimeStamp } } impl Reflectable for Performance { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
{ let timing = JS::from_rooted(&PerformanceTiming::new(window).root().root_ref()); Performance { reflector_: Reflector::new(), timing: timing, } }
identifier_body
performance.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::performancetiming::{PerformanceTiming, PerformanceTimingMethods}; use dom::window::Window; use time; pub type DOMHighResTimeStamp = f64; #[deriving(Encodable)] pub struct Performance { reflector_: Reflector, timing: JS<PerformanceTiming>, } impl Performance { fn new_inherited(window: &JSRef<Window>) -> Performance { let timing = JS::from_rooted(&PerformanceTiming::new(window).root().root_ref()); Performance { reflector_: Reflector::new(), timing: timing, } } pub fn new(window: &JSRef<Window>) -> Temporary<Performance> { let performance = Performance::new_inherited(window); reflect_dom_object(box performance, window, PerformanceBinding::Wrap) } } pub trait PerformanceMethods { fn Timing(&self) -> Temporary<PerformanceTiming>; fn Now(&self) -> DOMHighResTimeStamp; }
fn Timing(&self) -> Temporary<PerformanceTiming> { Temporary::new(self.timing.clone()) } fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().NavigationStartPrecise() as f64; (time::precise_time_s() - navStart) as DOMHighResTimeStamp } } impl Reflectable for Performance { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
random_line_split
performance.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::performancetiming::{PerformanceTiming, PerformanceTimingMethods}; use dom::window::Window; use time; pub type DOMHighResTimeStamp = f64; #[deriving(Encodable)] pub struct Performance { reflector_: Reflector, timing: JS<PerformanceTiming>, } impl Performance { fn new_inherited(window: &JSRef<Window>) -> Performance { let timing = JS::from_rooted(&PerformanceTiming::new(window).root().root_ref()); Performance { reflector_: Reflector::new(), timing: timing, } } pub fn new(window: &JSRef<Window>) -> Temporary<Performance> { let performance = Performance::new_inherited(window); reflect_dom_object(box performance, window, PerformanceBinding::Wrap) } } pub trait PerformanceMethods { fn Timing(&self) -> Temporary<PerformanceTiming>; fn Now(&self) -> DOMHighResTimeStamp; } impl<'a> PerformanceMethods for JSRef<'a, Performance> { fn
(&self) -> Temporary<PerformanceTiming> { Temporary::new(self.timing.clone()) } fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().NavigationStartPrecise() as f64; (time::precise_time_s() - navStart) as DOMHighResTimeStamp } } impl Reflectable for Performance { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
Timing
identifier_name