file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
qa_random.py
#!/usr/bin/env python # # Copyright 2006,2007,2010,2015 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at ...
x = np.zeros(num) y = np.zeros(num) rndm0 = gr.random(42); # init with fix seed 1 for k in range(num): x[k] = rndm0.ran1(); rndm1.reseed(43); # init with fix seed 2 for k in range(num): y[k] = rndm0.ran1(); for k in range(num): ...
x = rndm0.ran1(); y = rndm1.ran1(); self.assertEqual(x,y)
conditional_block
qa_random.py
#!/usr/bin/env python # # Copyright 2006,2007,2010,2015 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at ...
(gr_unittest.TestCase): # NOTE: For tests on the output distribution of the random numbers, see gnuradio-runtime/apps/evaluation_random_numbers.py. # Check for range [0,1) of uniform distributed random numbers def test_1(self): num_tests = 10000 values = np.zeros(num_tests) rndm = ...
test_random
identifier_name
qa_random.py
#!/usr/bin/env python # # Copyright 2006,2007,2010,2015 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at ...
if __name__ == '__main__': gr_unittest.run(test_random, "test_random.xml")
num = 5 rndm0 = gr.random(42); # init with time rndm1 = gr.random(42); # init with fix seed for k in range(num): x = rndm0.ran1(); y = rndm1.ran1(); self.assertEqual(x,y) x = np.zeros(num) y = np.zeros(num) rndm0 = gr.random(42); # in...
identifier_body
send_request_operator.py
#coding: utf-8 from flask import current_app from flask_restplus import marshal from APITaxi_models.hail import Hail, HailLog from ..descriptors.hail import hail_model from ..extensions import celery, redis_store_saved import requests, json @celery.task() def
(hail_id, endpoint, operator_header_name, operator_api_key, operator_email): operator_api_key = operator_api_key.encode('utf-8') operator_header_name = operator_header_name.encode('utf-8') hail = Hail.cache.get(hail_id) if not hail: current_app.logger.error('Unable to find hail: {}'.form...
send_request_operator
identifier_name
send_request_operator.py
#coding: utf-8 from flask import current_app from flask_restplus import marshal from APITaxi_models.hail import Hail, HailLog from ..descriptors.hail import hail_model from ..extensions import celery, redis_store_saved import requests, json @celery.task() def send_request_operator(hail_id, endpoint, operator_header_n...
operator_email, endpoint, headers)) current_app.logger.error(e) hail_log.store(None, redis_store_saved, str(e)) if r: hail_log.store(r, redis_store_saved) if not r or r.status_code < 200 or r.status_code >= 300: hail.status = 'failure' current_app....
) except requests.exceptions.RequestException as e: current_app.logger.error('Error calling: {}, endpoint: {}, headers: {}'.format(
random_line_split
send_request_operator.py
#coding: utf-8 from flask import current_app from flask_restplus import marshal from APITaxi_models.hail import Hail, HailLog from ..descriptors.hail import hail_model from ..extensions import celery, redis_store_saved import requests, json @celery.task() def send_request_operator(hail_id, endpoint, operator_header_n...
hail_log = HailLog('POST to operator', hail, data) try: r = requests.post(endpoint, data=data, headers=headers ) except requests.exceptions.RequestException as e: current_app.logger.error('Error calling: {}, endpoint: {}...
operator_api_key = operator_api_key.encode('utf-8') operator_header_name = operator_header_name.encode('utf-8') hail = Hail.cache.get(hail_id) if not hail: current_app.logger.error('Unable to find hail: {}'.format(hail_id)) return False headers = {'Content-Type': 'application/json', ...
identifier_body
send_request_operator.py
#coding: utf-8 from flask import current_app from flask_restplus import marshal from APITaxi_models.hail import Hail, HailLog from ..descriptors.hail import hail_model from ..extensions import celery, redis_store_saved import requests, json @celery.task() def send_request_operator(hail_id, endpoint, operator_header_n...
else: current_app.logger.error('No JSON in operator answer of {} : {}'.format( operator_email, r.text)) hail.status = 'received_by_operator' current_app.extensions['sqlalchemy'].db.session.commit() return True
hail.taxi_phone_number = unicode(r_json['data'][0]['taxi_phone_number'])
conditional_block
modo_extension.py
# -*- coding: utf-8 -*- """ Amavis management frontend. Provides: * SQL quarantine management * Per-domain settings """ from __future__ import unicode_literals from django.utils.translation import ugettext_lazy from modoboa.admin.models import Domain from modoboa.core.extensions import ModoExtension, exts_pool f...
(self): param_tools.registry.add("global", forms.ParametersForm, "Amavis") param_tools.registry.add( "user", forms.UserSettings, ugettext_lazy("Quarantine")) def load_initial_data(self): """Create records for existing domains and co.""" for dom in Domain.objects.all(): ...
load
identifier_name
modo_extension.py
# -*- coding: utf-8 -*- """ Amavis management frontend. Provides: * SQL quarantine management * Per-domain settings """ from __future__ import unicode_literals from django.utils.translation import ugettext_lazy
from modoboa.admin.models import Domain from modoboa.core.extensions import ModoExtension, exts_pool from modoboa.parameters import tools as param_tools from . import __version__, forms from .lib import create_user_and_policy, create_user_and_use_policy class Amavis(ModoExtension): """The Amavis extension.""" ...
random_line_split
modo_extension.py
# -*- coding: utf-8 -*- """ Amavis management frontend. Provides: * SQL quarantine management * Per-domain settings """ from __future__ import unicode_literals from django.utils.translation import ugettext_lazy from modoboa.admin.models import Domain from modoboa.core.extensions import ModoExtension, exts_pool f...
exts_pool.register_extension(Amavis)
"""Create records for existing domains and co.""" for dom in Domain.objects.all(): policy = create_user_and_policy("@{0}".format(dom.name)) for domalias in dom.domainalias_set.all(): domalias_pattern = "@{0}".format(domalias.name) create_user_and_use_polic...
identifier_body
modo_extension.py
# -*- coding: utf-8 -*- """ Amavis management frontend. Provides: * SQL quarantine management * Per-domain settings """ from __future__ import unicode_literals from django.utils.translation import ugettext_lazy from modoboa.admin.models import Domain from modoboa.core.extensions import ModoExtension, exts_pool f...
exts_pool.register_extension(Amavis)
domalias_pattern = "@{0}".format(domalias.name) create_user_and_use_policy(domalias_pattern, policy)
conditional_block
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*; fn main() { let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("piston: image", [300, 300]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let asset...
image(&rust_logo, c.transform, g); }); } }
window.set_lazy(true); while let Some(e) = window.next() { window.draw_2d(&e, |c, g, _| { clear([1.0; 4], g);
random_line_split
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*; fn main()
window.draw_2d(&e, |c, g, _| { clear([1.0; 4], g); image(&rust_logo, c.transform, g); }); } }
{ let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("piston: image", [300, 300]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); ...
identifier_body
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*; fn
() { let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new("piston: image", [300, 300]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap()...
main
identifier_name
unicode.js
/** * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md. */ /** * Set of utils to handle unicode characters. * * @module utils/unicode */ /** * Checks whether given `character` is a combining mark. * * @param {String} character Character to ...
/** * Checks whether given `character` is a low half of surrogate pair. * * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair * consist of high surrogate pair character followed by low surrogate pair character. * * @param {String} character Charac...
{ return !!character && character.length == 1 && /[\ud800-\udbff]/.test( character ); }
identifier_body
unicode.js
/** * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md. */ /** * Set of utils to handle unicode characters. * * @module utils/unicode */ /** * Checks whether given `character` is a combining mark. * * @param {String} character Character to ...
* @returns {Boolean} */ export function isInsideCombinedSymbol( string, offset ) { return isCombiningMark( string.charAt( offset ) ); }
random_line_split
unicode.js
/** * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md. */ /** * Set of utils to handle unicode characters. * * @module utils/unicode */ /** * Checks whether given `character` is a combining mark. * * @param {String} character Character to ...
( character ) { return !!character && character.length == 1 && /[\ud800-\udbff]/.test( character ); } /** * Checks whether given `character` is a low half of surrogate pair. * * Using UTF-16 terminology, a surrogate pair denotes UTF-16 character using two UTF-8 characters. The surrogate pair * consist of high sur...
isHighSurrogateHalf
identifier_name
character-count.component.fixture.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild, } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; import { SkyCharacterCounterInputDirective } from '../character-counter.directive'; @Component({ selector: 'sky-character-count-t...
(limit: number): void { this.maxCharacterCount = limit; this.changeDetector.markForCheck(); } }
setCharacterCountLimit
identifier_name
character-count.component.fixture.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild, } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { SkyCharacterCounterInputDirective } from '../character-counter.directive'; @Component({ selector: 'sky-character-count-test', templateUrl: './character-count.component.fixture.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class CharacterCountTestComponent implements OnInit { publi...
random_line_split
editorScrollbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public onThemeChanged(e: viewEvents.ViewThemeChangedEvent): boolean { this.scrollbar.updateClassName('editor-scrollable' + ' ' + getThemeTypeSelector(this._context.theme.type)); return true; } // --- end event handlers public prepareRender(ctx: RenderingContext): void { // Nothing to do } public render(...
{ return true; }
identifier_body
editorScrollbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this._context.viewLayout.setScrollPositionNow(newScrollPosition); }; // I've seen this happen both on the view dom node & on the lines content dom node. this._register(dom.addDisposableListener(viewDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(viewDomNode.domNode, true, true))); this._...
{ let deltaLeft = domNode.scrollLeft; if (deltaLeft) { newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft; domNode.scrollLeft = 0; } }
conditional_block
editorScrollbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} public delegateVerticalScrollbarMouseDown(browserEvent: IMouseEvent): void { this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent); } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { if (e.viewInfo) { const editor = this._contex...
} public getDomNode(): FastDomNode<HTMLElement> { return this.scrollbarDomNode;
random_line_split
editorScrollbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): void { super.dispose(); } private _setLayout(): void { const layoutInfo = this._context.configuration.editor.layoutInfo; this.scrollbarDomNode.setLeft(layoutInfo.contentLeft); const side = this._context.configuration.editor.viewInfo.minimap.side; if (side === 'right') { this.scrollbarDomNode.setWi...
dispose
identifier_name
aurelia-history-browser.d.ts
declare module 'aurelia-history-browser/index' { import { History } from 'aurelia-history'; export class BrowserHistory extends History { interval: any; active: any; previousFragment: any; location: any; history: any; root: any;
private _hasPushState; private _wantsHashChange; private _wantsPushState; private _checkUrlInterval; constructor(); getHash(window?: any): any; getFragment(fragment?: any, forcePushState?: any): any; activate(options?: any): any; deactivate(): void; checkUrl(): boolean;...
options: any; fragment: any; iframe: any; private _checkUrlCallback;
random_line_split
aurelia-history-browser.d.ts
declare module 'aurelia-history-browser/index' { import { History } from 'aurelia-history'; export class
extends History { interval: any; active: any; previousFragment: any; location: any; history: any; root: any; options: any; fragment: any; iframe: any; private _checkUrlCallback; private _hasPushState; private _wantsHashChange; private _wantsPushState; ...
BrowserHistory
identifier_name
Platform.py
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
# __revision__ = "test/Platform.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" import TestSCons test = TestSCons.TestSCons() test.write('SConstruct', """ env = Environment() Platform('cygwin')(env) print "'%s'" % env['PROGSUFFIX'] assert env['SHELL'] == 'sh' Platform('os2')(env) print "'%s'" % env['PR...
random_line_split
portal.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.controllers.portal import PortalAccount from odoo.http import request class PortalAccount(PortalAccount): def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): ...
values.update(payment_inputs) # if the current user is connected we set partner_id to his partner otherwise we set it as the invoice partner # we do this to force the creation of payment tokens to the correct partner and avoid token linked to the public user values['partner_id'] = invoi...
payment_inputs.pop('pms', None) token_count = request.env['payment.token'].sudo().search_count([('acquirer_id.company_id', '=', invoice.company_id.id), ('partner_id', '=', invoice.partner_id.id), ...
conditional_block
portal.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.controllers.portal import PortalAccount from odoo.http import request class PortalAccount(PortalAccount): def
(self, invoice, access_token, **kwargs): values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) payment_inputs = request.env['payment.acquirer']._get_available_payment_input(partner=invoice.partner_id, company=invoice.company_id) # if not connected (us...
_invoice_get_page_view_values
identifier_name
portal.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.controllers.portal import PortalAccount from odoo.http import request class PortalAccount(PortalAccount): def _invoice_get_page_view_values(self, invoice, access_token, **kwargs):
values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) payment_inputs = request.env['payment.acquirer']._get_available_payment_input(partner=invoice.partner_id, company=invoice.company_id) # if not connected (using public user), the method _get_available_payme...
identifier_body
portal.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.controllers.portal import PortalAccount
def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) payment_inputs = request.env['payment.acquirer']._get_available_payment_input(partner=invoice.partner_id, company=invoice.comp...
from odoo.http import request class PortalAccount(PortalAccount):
random_line_split
debug.js
'use strict'; var fs = require('fs'); var path = require('path'); var util = require('util'); var dbg = require('debug'); // process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log'; var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null; module.ex...
args = args.map(function (arg) { if (typeof arg === 'string') return arg; return JSON.stringify(arg); }); out && out.write(util.format.apply(util, args) + '\n'); out || log.apply(null, args); }; }
{ args[_key] = arguments[_key]; }
conditional_block
debug.js
'use strict'; var fs = require('fs'); var path = require('path'); var util = require('util'); var dbg = require('debug'); // process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log'; var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null; module.ex...
{ var log = dbg(namespace); return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args = args.map(function (arg) { if (typeof arg === 'string') return arg; return JSON.stringify(arg); }); ou...
identifier_body
debug.js
'use strict'; var fs = require('fs'); var path = require('path'); var util = require('util'); var dbg = require('debug'); // process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log'; var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null; module.ex...
(namespace) { var log = dbg(namespace); return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args = args.map(function (arg) { if (typeof arg === 'string') return arg; return JSON.stringify(arg); ...
debug
identifier_name
debug.js
'use strict'; var fs = require('fs'); var path = require('path'); var util = require('util'); var dbg = require('debug'); // process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log'; var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null; module.ex...
// // The added benefit is with the TABTAB_DEBUG environment variable, which when // defined, will write debug output to the specified filename. // // Usefull when debugging tab completion, as logs on stdout / stderr are either // shallowed or used as tab completion results. // // namespace - The String namespace to us...
random_line_split
permission-assign.component.ts
import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { NgOption } from '@ng-select/ng-select'; import { TabService } from '../../../../common/services/tab.service'; import { PermissionService } fr...
() { this.permissionAssignForm = new FormGroup({ name: new FormControl({value: '', disabled: true}, Validators.required), description: new FormControl({value: '', disabled: true}, Validators.required), role: new FormControl() }); } /* Method: submitform Description: Trigger when...
createAssignForm
identifier_name
permission-assign.component.ts
import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { NgOption } from '@ng-select/ng-select'; import { TabService } from '../../../../common/services/tab.service'; import { PermissionService } fr...
let assignedRoles = this.permissionAssignForm.value.role; let roles = []; assignedRoles.map(role => { roles.push({"role_id":role}); }); this.roleAssignData = {"roles": roles}; this.permissionService.assignPermission(this.selectedPermission, this.roleAssignData).subscribe(role => { ...
return; }
random_line_split
permission-assign.component.ts
import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { NgOption } from '@ng-select/ng-select'; import { TabService } from '../../../../common/services/tab.service'; import { PermissionService } fr...
name: permission.name, description: permission.description, role: this.selectedPermissionRoles }); }); } }); },error => { console.log("error", error); }); } /* Method: createEditForm Description: Create User ...
{ this.roles = []; this.roleData = []; this.selectedPermissionRoles = []; this.roleService.getRoles().subscribe((role: Array<object>) => { role.map((role:any) => { this.roles.push({ id: role.role_id, name: role.name }) }); this.roleData = this.roles; this.permissionServ...
identifier_body
permission-assign.component.ts
import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { NgOption } from '@ng-select/ng-select'; import { TabService } from '../../../../common/services/tab.service'; import { PermissionService } fr...
}); this.permissionAssignForm.patchValue({ name: permission.name, description: permission.description, role: this.selectedPermissionRoles }); }); } }); },error => { console.log("error", error); }); ...
{ this.selectedPermissionRoles.push(role.role_id); }
conditional_block
skip_split_operation.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::DIRECTIVE_SPLIT_OPERATION; use common::NamedItem; use graphql_ir::{FragmentDefinition, OperationDefinition, Program, T...
else { Transformed::Keep } } fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> { Transformed::Keep } }
{ Transformed::Delete }
conditional_block
skip_split_operation.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::DIRECTIVE_SPLIT_OPERATION; use common::NamedItem; use graphql_ir::{FragmentDefinition, OperationDefinition, Program, T...
Transformed::Delete } else { Transformed::Keep } } fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> { Transformed::Keep } }
.directives .named(*DIRECTIVE_SPLIT_OPERATION) .is_some() {
random_line_split
skip_split_operation.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::DIRECTIVE_SPLIT_OPERATION; use common::NamedItem; use graphql_ir::{FragmentDefinition, OperationDefinition, Program, T...
( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { if operation .directives .named(*DIRECTIVE_SPLIT_OPERATION) .is_some() { Transformed::Delete } else { Transformed::Keep } ...
transform_operation
identifier_name
skip_split_operation.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::DIRECTIVE_SPLIT_OPERATION; use common::NamedItem; use graphql_ir::{FragmentDefinition, OperationDefinition, Program, T...
pub struct SkipSplitOperation; impl Transformer for SkipSplitOperation { const NAME: &'static str = "SkipSplitOperationTransform"; const VISIT_ARGUMENTS: bool = false; const VISIT_DIRECTIVES: bool = false; fn transform_operation( &mut self, operation: &OperationDefinition, ) -> T...
{ let mut transform = SkipSplitOperation {}; transform .transform_program(program) .replace_or_else(|| program.clone()) }
identifier_body
cloudspeech_demo.py
#!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
continue logging.info('You said: "%s"' % text) text = text.lower() if 'turn on the light' in text: board.led.state = Led.ON elif 'turn off the light' in text: board.led.state = Led.OFF elif 'blink the light' in ...
if text is None: logging.info('You said nothing.')
random_line_split
cloudspeech_demo.py
#!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
def main(): logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(description='Assistant service example.') parser.add_argument('--language', default=locale_language()) args = parser.parse_args() logging.info('Initializing for language %s...', args.language) hints = get_h...
language, _ = locale.getdefaultlocale() return language
identifier_body
cloudspeech_demo.py
#!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
text = client.recognize(language_code=args.language, hint_phrases=hints) if text is None: logging.info('You said nothing.') continue logging.info('You said: "%s"' % text) text = text.lower() ...
logging.info('Say something.')
conditional_block
cloudspeech_demo.py
#!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): language, _ = locale.getdefaultlocale() return language def main(): logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(description='Assistant service example.') parser.add_argument('--language', default=locale_language()) args = parser.parse_args() logging.info(...
locale_language
identifier_name
index.tsx
checkVersion from './bootstrap/checkVersion' import { ColorInfo, ModeInfo } from './interface' let backPressClickTimeStamp = 0 declare var global global.toast = () => {} const netInfoHandler = (reach) => { global.netInfo = reach } const shouldChangeBackground = Platform.OS !== 'android' || (Platform.OS === 'and...
bronze: '铜', isSigned: true, exp: '' }, isNightMode: false, colorTheme: 'lightBlue' }, colorTheme: 'lightBlue', secondaryColor: 'pink', loadingText: 'P9 · 酷玩趣友' } } switchModeOnR oot = (theme) => { if (!theme) { let targetS...
{ super(props) const { height, width } = Dimensions.get('window') this.state = { text: '', width, height, minWidth: Math.min(height, width), isNightMode: false, tipBarMarginBottom: new Animated.Value(0), progress: new Animated.Value(0), isLoadingAsyncStorage: ...
identifier_body
index.tsx
backPressClickTimeStamp = 0 declare var global global.toast = () => {} const netInfoHandler = (reach) => { global.netInfo = reach } const shouldChangeBackground = Platform.OS !== 'android' || (Platform.OS === 'android' && Platform.Version <= 20) export default class Root extends React.Component<any, any> { st...
} = currentScreen tracker.trackScreenView(routeName) } // if (screens.includes(current
conditional_block
index.tsx
', secondaryColor: 'pink', loadingText: 'P9 · 酷玩趣友' } } switchModeOnRoot = (theme) => { if (!theme) { let targetState = !this.state.isNightMode this.setState({ isNightMode: targetState }) return AsyncStorage.setItem('@Theme:isNightMode', targetState.toString()) ...
random_line_split
index.tsx
Version from './bootstrap/checkVersion' import { ColorInfo, ModeInfo } from './interface' let backPressClickTimeStamp = 0 declare var global global.toast = () => {} const netInfoHandler = (reach) => { global.netInfo = reach } const shouldChangeBackground = Platform.OS !== 'android' || (Platform.OS === 'android' ...
oast = this.toast BackHandler.addEventListener('hardwareBackPress', () => { let timestamp: any = new Date() if (timestamp - backPressClickTimeStamp > 2000) { backPressClickTimeStamp = timestamp global.toast && global.toast('再按一次退出程序') return true } else { return fal...
t() { global.t
identifier_name
entry.rs
use memory::Frame; pub struct Entry(u64); impl Entry { pub fn is_unused(&self) -> bool
pub fn set_unused(&mut self) { self.0 = 0; } pub fn flags(&self) -> EntryFlags { EntryFlags::from_bits_truncate(self.0) } pub fn pointed_frame(&self) -> Option<Frame> { if self.flags().contains(PRESENT) { Some(Frame::containing_address(self.0 as usize & 0x000f...
{ self.0 == 0 }
identifier_body
entry.rs
use memory::Frame; pub struct Entry(u64); impl Entry { pub fn is_unused(&self) -> bool { self.0 == 0 } pub fn set_unused(&mut self) { self.0 = 0; } pub fn flags(&self) -> EntryFlags { EntryFlags::from_bits_truncate(self.0) } pub fn pointed_frame(&self) -> Option<...
} pub fn set(&mut self, frame: Frame, flags: EntryFlags) { assert!(frame.start_address() & !0x000fffff_fffff000 == 0); self.0 = (frame.start_address() as u64) | flags.bits(); } } bitflags! { flags EntryFlags: u64 { const PRESENT = 1 << 0, const WRITABLE = ...
{ None }
conditional_block
entry.rs
use memory::Frame; pub struct Entry(u64); impl Entry { pub fn is_unused(&self) -> bool { self.0 == 0 } pub fn
(&mut self) { self.0 = 0; } pub fn flags(&self) -> EntryFlags { EntryFlags::from_bits_truncate(self.0) } pub fn pointed_frame(&self) -> Option<Frame> { if self.flags().contains(PRESENT) { Some(Frame::containing_address(self.0 as usize & 0x000fffff_fffff000)) ...
set_unused
identifier_name
entry.rs
use memory::Frame;
pub fn is_unused(&self) -> bool { self.0 == 0 } pub fn set_unused(&mut self) { self.0 = 0; } pub fn flags(&self) -> EntryFlags { EntryFlags::from_bits_truncate(self.0) } pub fn pointed_frame(&self) -> Option<Frame> { if self.flags().contains(PRESENT) { ...
pub struct Entry(u64); impl Entry {
random_line_split
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use compositor...
{ Click(MouseButton, TypedPoint2D<f32, DevicePixel>), MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>), MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>), } #[derive(Clone)] pub enum WindowNavigateMsg { Forward, Back, } /// Events that the windowing system sends to Servo. #[derive(Clone)...
MouseWindowEvent
identifier_name
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use compositor...
fn present(&self); /// Return the size of the window with head and borders and position of the window values fn client_window(&self) -> (Size2D<u32>, Point2D<i32>); /// Set the size inside of borders and head fn set_inner_size(&self, size: Size2D<u32>); /// Set the window position fn set_po...
random_line_split
hr_contract.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(self, cr, uid, ids, context=None): for contract in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context): if contract['date_start'] and contract['date_end'] and contract['date_start'] > contract['date_end']: return False return True _constraints = [ ...
_check_dates
identifier_name
hr_contract.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
_defaults = { 'date_start': lambda *a: time.strftime("%Y-%m-%d"), 'type_id': _get_type } def onchange_employee_id(self, cr, uid, ids, employee_id, context=None): if not employee_id: return {'value': {'job_id': False}} emp_obj = self.pool.get('hr.employee').brow...
type_ids = self.pool.get('hr.contract.type').search(cr, uid, [('name', '=', 'Employee')]) return type_ids and type_ids[0] or False
identifier_body
hr_contract.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
_description = "Employee" _inherit = "hr.employee" def _get_latest_contract(self, cr, uid, ids, field_name, args, context=None): res = {} obj_contract = self.pool.get('hr.contract') for emp in self.browse(cr, uid, ids, context=context): contract_ids = obj_contract.search...
from openerp.osv import fields, osv class hr_employee(osv.osv): _name = "hr.employee"
random_line_split
hr_contract.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
return {'value': {'job_id': job_id}} def _check_dates(self, cr, uid, ids, context=None): for contract in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context): if contract['date_start'] and contract['date_end'] and contract['date_start'] > contract['date_end']: ...
job_id = emp_obj.job_id.id
conditional_block
ansi-colors.js
(function(){var test = require('tape'); var table = require('../'); var color = require('cli-color'); var ansiTrim = require('cli-color/lib/trim'); test('center', function (t) { t.plan(1); var opts = { align: [ 'l', 'c', 'l' ], stringLength: function(s) { return ansiTrim(s).length } }; ...
}); })();
].join('\n'));
random_line_split
currentTable.js
import { GET_TABLE_CONTENT, CONNECT, CHANGE_VIEW_MODE } from '../actions/currentTable'; export default function currentTable(currentTableDefault = { items: [], isConnected: false, isFetching: true, totalCount: 0, order: [], page: 1, isContent: true, structureTable: [], titleTable: [] }, action)
} }
{ switch (action.type) { case GET_TABLE_CONTENT: return { items: action.currentTable !== undefined ? action.currentTable : currentTableDefault.items, isFetching: action.isFetching, isConnected: true, totalCount: action.totalCount !== undefined ? action.totalCount : currentTab...
identifier_body
currentTable.js
import { GET_TABLE_CONTENT, CONNECT, CHANGE_VIEW_MODE } from '../actions/currentTable'; export default function
(currentTableDefault = { items: [], isConnected: false, isFetching: true, totalCount: 0, order: [], page: 1, isContent: true, structureTable: [], titleTable: [] }, action) { switch (action.type) { case GET_TABLE_CONTENT: return { items: action.currentTable !== undefined ? action.cu...
currentTable
identifier_name
currentTable.js
import { GET_TABLE_CONTENT, CONNECT, CHANGE_VIEW_MODE } from '../actions/currentTable';
isConnected: false, isFetching: true, totalCount: 0, order: [], page: 1, isContent: true, structureTable: [], titleTable: [] }, action) { switch (action.type) { case GET_TABLE_CONTENT: return { items: action.currentTable !== undefined ? action.currentTable : currentTableDefault.items...
export default function currentTable(currentTableDefault = { items: [],
random_line_split
hash_file.py
import hashlib from core.analytics import InlineAnalytics from core.observables import Hash HASH_TYPES_DICT = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } class HashFile(InlineAnalytics):
) f.hashes.append({"hash": hash_type, "value": h.hexdigest()}) f.save() @staticmethod def extract_hashes(body_contents): hashers = {k: HASH_TYPES_DICT[k]() for k in HASH_TYPES_DICT} while True: chunk = body_contents.read(512 * 16) ...
default_values = { "name": "HashFile", "description": "Extracts MD5, SHA1, SHA256, SHA512 hashes from file", } ACTS_ON = ["File", "Certificate"] @staticmethod def each(f): if f.body: f.hashes = [] for hash_type, h in HashFile.extract_hashes(f.body.conten...
identifier_body
hash_file.py
import hashlib from core.analytics import InlineAnalytics from core.observables import Hash HASH_TYPES_DICT = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } class HashFile(InlineAnalytics): default_values = { "name": "HashFile", ...
(body_contents): hashers = {k: HASH_TYPES_DICT[k]() for k in HASH_TYPES_DICT} while True: chunk = body_contents.read(512 * 16) if not chunk: break for h in hashers.values(): h.update(chunk) return hashers.items()
extract_hashes
identifier_name
hash_file.py
import hashlib from core.analytics import InlineAnalytics from core.observables import Hash HASH_TYPES_DICT = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } class HashFile(InlineAnalytics): default_values = { "name": "HashFile", ...
for h in hashers.values(): h.update(chunk) return hashers.items()
break
conditional_block
hash_file.py
import hashlib from core.analytics import InlineAnalytics from core.observables import Hash HASH_TYPES_DICT = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } class HashFile(InlineAnalytics): default_values = { "name": "HashFile", ...
hash_object.save() f.active_link_to( hash_object, "{} hash".format(hash_type.upper()), "HashFile", clean_old=False, ) f.hashes.append({"hash": hash_type, "value": h.hexdigest()...
for hash_type, h in HashFile.extract_hashes(f.body.contents): hash_object = Hash.get_or_create(value=h.hexdigest()) hash_object.add_source("analytics")
random_line_split
from_form.rs
use request::FormItems; /// Trait to create an instance of some type from an HTTP form. The /// [Form](struct.Form.html) type requires that its generic parameter implements /// this trait. /// /// This trait can be automatically derived via the /// [rocket_codegen](/rocket_codegen) plugin: /// /// ```rust /// #![featu...
/// [FormItems](struct.FormItems.html) iterator to iterate through the form /// key/value pairs. Be aware that form fields that are typically hidden from /// your application, such as `_method`, will be present while iterating. pub trait FromForm<'f>: Sized { /// The associated error to be returned when parsing fai...
random_line_split
from_form.rs
use request::FormItems; /// Trait to create an instance of some type from an HTTP form. The /// [Form](struct.Form.html) type requires that its generic parameter implements /// this trait. /// /// This trait can be automatically derived via the /// [rocket_codegen](/rocket_codegen) plugin: /// /// ```rust /// #![featu...
}
{ items.mark_complete(); Ok(items.inner_str()) }
identifier_body
from_form.rs
use request::FormItems; /// Trait to create an instance of some type from an HTTP form. The /// [Form](struct.Form.html) type requires that its generic parameter implements /// this trait. /// /// This trait can be automatically derived via the /// [rocket_codegen](/rocket_codegen) plugin: /// /// ```rust /// #![featu...
(items: &mut FormItems<'f>) -> Result<Self, Self::Error> { items.mark_complete(); Ok(items.inner_str()) } }
from_form_items
identifier_name
disassembler.py
#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===---------------------------------...
(LLVMObject): """Represents a disassembler instance. Disassembler instances are tied to specific "triple," which must be defined at creation time. Disassembler instances can disassemble instructions from multiple sources. """ def __init__(self, triple): """Create a new disassembler ins...
Disassembler
identifier_name
disassembler.py
#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===---------------------------------...
def register_library(library): library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int, callbacks['op_info'], callbacks['symbol_lookup']] library.LLVMCreateDisasm.restype = c_object_p library.LLVMDisasmDispose.argtypes = [Disassembler] library.LLVMDisasmInstruction.argtypes = [Disass...
if not lib.LLVMSetDisasmOptions(self, options): raise Exception('Unable to set all disassembler options in %i' % options)
identifier_body
disassembler.py
#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===---------------------------------...
def _ensure_initialized(): global _initialized if not _initialized: # Here one would want to call the functions # LLVMInitializeAll{TargetInfo,TargetMC,Disassembler}s, but # unfortunately they are only defined as static inline # functions in the header files of llvm-c, so they do...
_initialized = False _targets = ['AArch64', 'ARM', 'Hexagon', 'MSP430', 'Mips', 'NVPTX', 'PowerPC', 'R600', 'Sparc', 'SystemZ', 'X86', 'XCore']
random_line_split
disassembler.py
#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===---------------------------------...
_initialized = True class Disassembler(LLVMObject): """Represents a disassembler instance. Disassembler instances are tied to specific "triple," which must be defined at creation time. Disassembler instances can disassemble instructions from multiple sources. """ def __init__(self, ...
try: f = getattr(lib, "LLVMInitialize" + tgt + initializer) except AttributeError: continue f()
conditional_block
index.d.ts
* * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
/* * @license Apache-2.0
random_line_split
workernavigator.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::WorkerNavigatorBinding; use dom::bindings::codegen::Bindings::WorkerNavigato...
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname fn AppName(&self) -> DOMString { navigatorinfo::AppName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename fn AppCodeName(&self) -> DOMString { navigatorinfo::AppCodeName() } // https://...
fn TaintEnabled(&self) -> bool { navigatorinfo::TaintEnabled() }
random_line_split
workernavigator.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::WorkerNavigatorBinding; use dom::bindings::codegen::Bindings::WorkerNavigato...
pub fn new(global: &WorkerGlobalScope) -> Root<WorkerNavigator> { reflect_dom_object(box WorkerNavigator::new_inherited(), global, WorkerNavigatorBinding::Wrap) } } impl WorkerNavigatorMethods for WorkerNavigator { // https://html.spec.whatwg....
{ WorkerNavigator { reflector_: Reflector::new(), } }
identifier_body
workernavigator.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::WorkerNavigatorBinding; use dom::bindings::codegen::Bindings::WorkerNavigato...
(&self) -> DOMString { navigatorinfo::Platform() } // https://html.spec.whatwg.org/multipage/#dom-navigator-useragent fn UserAgent(&self) -> DOMString { navigatorinfo::UserAgent() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appversion fn AppVersion(&self) -> DOMS...
Platform
identifier_name
common.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
import contextlib import ftplib import os import uuid import paramiko from nova.openstack.common import log as logging from nova.openstack.common import processutils from nova.virt.powervm import constants from nova.virt.powervm import exception LOG = logging.getLogger(__name__) class Connection(object): def ...
random_line_split
common.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
(): rmkey = 'rm %s*' % KEY_BASE_NAME run_command(src_conn_obj, rmkey) def insert_into_authorized_keys(public_key): echo_key = 'echo "%s" >> .ssh/authorized_keys' % public_key ssh_command_as_root(dest_conn_obj, echo_key) def remove_from_authorized_keys(): rmkey = ('sed /...
cleanup_key_on_source
identifier_name
common.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
raise exception.PowerVMFTPTransferFailed(ftp_cmd='GET', source_path=remote_path, dest_path=local_path) def aix_path_join(path_one, path_two): """Ensures file path is built correctly for remote UNIX system :param path_one: string of the first file path :param path_two: string of t...
"""Retrieve a file via FTP :param connection: a Connection object. :param remote_path: path to the remote file :param local_path: path to local destination :raises: PowerVMFileTransferFailed """ try: ftp = ftplib.FTP(host=connection.host, user=connection.usernam...
identifier_body
common.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
final_path = path_one + '/' + path_two return final_path @contextlib.contextmanager def vios_to_vios_auth(source, dest, conn_info): """Context allowing for SSH between VIOS partitions This context will build an SSH key on the source host, put the key into the authorized_keys on the destination ...
path_two = path_two.lstrip('/')
conditional_block
efergy.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monitors home energy use as measured by an efergy engage hub using its (unofficial, undocumented) API. Configuration: To use the efergy sensor you will need to add something like the following to your config/configuration.yaml sensor: platform: efergy app_t...
""" homeassistant.components.sensor.efergy
random_line_split
efergy.py
""" homeassistant.components.sensor.efergy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monitors home energy use as measured by an efergy engage hub using its (unofficial, undocumented) API. Configuration: To use the efergy sensor you will need to add something like the following to your config/configurati...
@property def name(self): """ Returns the name. """ return self._name @property def state(self): """ Returns the state of the device. """ return self._state @property def unit_of_measurement(self): """ Unit of measurement of this entity, if any. """ ...
self._name = SENSOR_TYPES[sensor_type][0] self.type = sensor_type self.app_token = app_token self.utc_offset = utc_offset self._state = None self.period = period self.currency = currency if self.type == 'cost': self._unit_of_measurement = self.currency...
identifier_body
efergy.py
""" homeassistant.components.sensor.efergy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monitors home energy use as measured by an efergy engage hub using its (unofficial, undocumented) API. Configuration: To use the efergy sensor you will need to add something like the following to your config/configurati...
if variable['type'] not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable) else: dev.append(EfergySensor(variable['type'], app_token, utc_offset, variable['period'], variable['currency'])) add_devices(dev) # py...
variable['currency'] = ''
conditional_block
efergy.py
""" homeassistant.components.sensor.efergy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monitors home energy use as measured by an efergy engage hub using its (unofficial, undocumented) API. Configuration: To use the efergy sensor you will need to add something like the following to your config/configurati...
(self): """ Returns the name. """ return self._name @property def state(self): """ Returns the state of the device. """ return self._state @property def unit_of_measurement(self): """ Unit of measurement of this entity, if any. """ return self._unit_of_m...
name
identifier_name
string.d.ts
// Type definitions for @ag-grid-community/core v25.0.1 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> /** * It encodes any string in UTF-8 format * taken from https://github.com/mathiasbynens/utf8.js * @param {string} s * @returns {string} */ export declare funct...
* @return {string} */ export declare function camelCaseToHumanText(camelCase: string | undefined): string | null; export declare function startsWith(str: string, matchStart: string): boolean;
* from: https://stackoverflow.com/questions/15369566/putting-space-in-camel-case-string-using-regular-expression * @param {string} camelCase
random_line_split
hello_asyncio.py
# hello_asyncio.py import asyncio import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient try: import aioredis except ImportError: print("Please install aioredis: pip install aioredis") exit(0) class AsyncRequestHandler(tornado.web.RequestHandler): ""...
(self, loop): self.redis = loop.run_until_complete( aioredis.create_redis(('localhost', 6379), loop=loop) ) if __name__ == "__main__": print("Run hello_asyncio ... http://127.0.0.1:8888") application = Application() application.listen(8888) loop = asyncio.get_event_loop() ...
init_with_loop
identifier_name
hello_asyncio.py
# hello_asyncio.py import asyncio import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient try: import aioredis except ImportError: print("Please install aioredis: pip install aioredis") exit(0) class AsyncRequestHandler(tornado.web.RequestHandler):
"""Handle GET request asyncronously, delegates to ``self.get_async()`` coroutine. """ yield self._run_method('get', *args, **kwargs) @tornado.gen.coroutine def post(self, *args, **kwargs): """Handle POST request asyncronously, delegates to ``self.post_async()`` c...
"""Base class for request handlers with `asyncio` coroutines support. It runs methods on Tornado's ``AsyncIOMainLoop`` instance. Subclasses have to implement one of `get_async()`, `post_async()`, etc. Asynchronous method should be decorated with `@asyncio.coroutine`. Usage example:: class MyA...
identifier_body
hello_asyncio.py
# hello_asyncio.py import asyncio import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient try: import aioredis except ImportError: print("Please install aioredis: pip install aioredis") exit(0) class AsyncRequestHandler(tornado.web.RequestHandler): ""...
future_ = tornado.concurrent.Future() asyncio.async( self._run_async(coroutine, future_, *args, **kwargs) ) return future_ class MainHandler(AsyncRequestHandler): @asyncio.coroutine def get_async(self): redis = self.application.redis yield from re...
raise tornado.web.HTTPError(405)
conditional_block
hello_asyncio.py
# hello_asyncio.py import asyncio import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient try: import aioredis except ImportError: print("Please install aioredis: pip install aioredis") exit(0) class AsyncRequestHandler(tornado.web.RequestHandler): ""...
self.write({'html': html}) You may also just re-define `get()` or `post()` methods and they will be simply run synchronously. This may be convinient for draft implementation, i.e. for testing new libs or concepts. """ @tornado.gen.coroutine def get(self, *args, **kwargs): ...
random_line_split
eye.py
# Speak.activity # A simple front end to the espeak text-to-speech engine on the XO laptop # http://wiki.laptop.org/go/Speak # # Copyright (C) 2008 Joshua Minor # This file is part of Speak.activity # # Parts of Speak.activity are based on code from Measure.activity # Copyright (C) 2007 Arjun Sarwal - arjun@laptop.or...
return cx, a.height * 0.6 EYE_X, EYE_Y = self.translate_coordinates( self.get_toplevel(), a.width // 2, a.height // 2) EYE_HWIDTH = a.width EYE_HHEIGHT = a.height BALL_DIST = EYE_HWIDTH / 4 dx = self.x - EYE_X dy = self.y - EYE_Y if dx ...
cx = a.width * 0.4
conditional_block
eye.py
# Speak.activity # A simple front end to the espeak text-to-speech engine on the XO laptop # http://wiki.laptop.org/go/Speak # # Copyright (C) 2008 Joshua Minor # This file is part of Speak.activity # # Parts of Speak.activity are based on code from Measure.activity # Copyright (C) 2007 Arjun Sarwal - arjun@laptop.or...
a = self.get_allocation() if self.x is None or self.y is None: # look ahead, but not *directly* in the middle pw = self.get_parent().get_allocation().width if a.x + a.width // 2 < pw // 2: cx = a.width * 0.6 else: cx = a.wi...
# Thanks to xeyes :) def computePupil(self):
random_line_split
eye.py
# Speak.activity # A simple front end to the espeak text-to-speech engine on the XO laptop # http://wiki.laptop.org/go/Speak # # Copyright (C) 2008 Joshua Minor # This file is part of Speak.activity # # Parts of Speak.activity are based on code from Measure.activity # Copyright (C) 2007 Arjun Sarwal - arjun@laptop.or...
(self): return False def look_at(self, x, y): self.x = x self.y = y self.queue_draw() def look_ahead(self): self.x = None self.y = None self.queue_draw() # Thanks to xeyes :) def computePupil(self): a = self.get_allocation() if ...
has_left_center_right
identifier_name
eye.py
# Speak.activity # A simple front end to the espeak text-to-speech engine on the XO laptop # http://wiki.laptop.org/go/Speak # # Copyright (C) 2008 Joshua Minor # This file is part of Speak.activity # # Parts of Speak.activity are based on code from Measure.activity # Copyright (C) 2007 Arjun Sarwal - arjun@laptop.or...
def look_ahead(self): self.x = None self.y = None self.queue_draw() # Thanks to xeyes :) def computePupil(self): a = self.get_allocation() if self.x is None or self.y is None: # look ahead, but not *directly* in the middle pw = self.get_par...
self.x = x self.y = y self.queue_draw()
identifier_body
feeds.py
"""(Re)builds feeds for categories""" import os import datetime import jinja2 from google.appengine.api import app_identity import dao import util def build_and_save_for_category(cat, store, prefix): """Build and save feeds for category""" feed = build_feed(cat) save_feeds(store, feed, prefix, cat.key.id...
class Feed(object): """Represents feed with torrent entries""" def __init__(self, title, link, ttl=60, description=None): self.title = title self.link = link self.description = description or title self.ttl = ttl self.items = [] self.lastBuildDate = None ...
xml = feed.render_short_rss() path = os.path.join(prefix, 'short', '{}.xml'.format(name)) store.put(path, xml.encode('utf-8'), 'application/rss+xml')
random_line_split
feeds.py
"""(Re)builds feeds for categories""" import os import datetime import jinja2 from google.appengine.api import app_identity import dao import util def build_and_save_for_category(cat, store, prefix): """Build and save feeds for category""" feed = build_feed(cat) save_feeds(store, feed, prefix, cat.key.id...
return 25 # category with subcategories
return 50
conditional_block
feeds.py
"""(Re)builds feeds for categories""" import os import datetime import jinja2 from google.appengine.api import app_identity import dao import util def build_and_save_for_category(cat, store, prefix): """Build and save feeds for category""" feed = build_feed(cat) save_feeds(store, feed, prefix, cat.key.id...
def feed_size(category): """Returns number of feed entries for category""" if category.key.id() == 'r0': # Root category return 100 elif category.key.id().startswith('c'): # Level 2 category return 50 return 25 # category with subcat...
jinja2_env = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'), # loader=PackageLoader('package_name', 'templates'), autoescape=True, extensions=['jinja2.ext.autoescape'] ) jinja2_env.filters['rfc822date'] = util.datetime_to_rfc822 return jinja2_env
identifier_body
feeds.py
"""(Re)builds feeds for categories""" import os import datetime import jinja2 from google.appengine.api import app_identity import dao import util def build_and_save_for_category(cat, store, prefix): """Build and save feeds for category""" feed = build_feed(cat) save_feeds(store, feed, prefix, cat.key.id...
(self): self.lastBuildDate = self.latest_item_dt env = make_jinja_env() template = env.get_template('rss_short.xml') return template.render(feed=self) def make_jinja_env(): jinja2_env = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'), # loader=Packag...
render_short_rss
identifier_name