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
definition.ts
import * as vscode from 'vscode' import {Extension} from '../main' import {tokenizer} from './tokenizer' export class
implements vscode.DefinitionProvider { extension: Extension constructor(extension: Extension) { this.extension = extension } public provideDefinition(document: vscode.TextDocument, position: vscode.Position, _token: vscode.CancellationToken) : Thenable<vscode.Location> { retur...
DefinitionProvider
identifier_name
definition.ts
import * as vscode from 'vscode' import {Extension} from '../main' import {tokenizer} from './tokenizer' export class DefinitionProvider implements vscode.DefinitionProvider { extension: Extension constructor(extension: Extension) { this.extension = extension } public provideDefinition(docum...
if (token in this.extension.completer.command.newcommandData) { const command = this.extension.completer.command.newcommandData[token] resolve(new vscode.Location( vscode.Uri.file(command.file), command.position )) return ...
{ const cite = this.extension.completer.citation.citationData[token] resolve(new vscode.Location( vscode.Uri.file(cite.file), cite.position )) return }
conditional_block
definition.ts
import * as vscode from 'vscode' import {Extension} from '../main' import {tokenizer} from './tokenizer' export class DefinitionProvider implements vscode.DefinitionProvider { extension: Extension constructor(extension: Extension)
public provideDefinition(document: vscode.TextDocument, position: vscode.Position, _token: vscode.CancellationToken) : Thenable<vscode.Location> { return new Promise((resolve, _reject) => { const token = tokenizer(document, position) if (token === undefined) { ...
{ this.extension = extension }
identifier_body
definition.ts
import * as vscode from 'vscode' import {Extension} from '../main' import {tokenizer} from './tokenizer' export class DefinitionProvider implements vscode.DefinitionProvider { extension: Extension constructor(extension: Extension) { this.extension = extension } public provideDefinition(docum...
} if (token in this.extension.completer.reference.referenceData) { const ref = this.extension.completer.reference.referenceData[token] resolve(new vscode.Location( vscode.Uri.file(ref.file), ref.item.position )) ...
if (token === undefined) { resolve() return
random_line_split
htmlulistelement.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::HTMLUListElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
{ htmlelement: HTMLElement } impl HTMLUListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement { HTMLUListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_ro...
HTMLUListElement
identifier_name
htmlulistelement.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::HTMLUListElementBinding; use dom::bindings::js::Root;
use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLUListElement { htmlelement: HTMLElement } impl HTMLUListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement { HTMLUListElement { htmlelement: HTMLElement::n...
use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement;
random_line_split
index.ts
import { CommonModule } from '@angular/common' import { RouterModule } from '@angular/router'; import { NgModule } from '@angular/core'; import AsesorModule from '../asesor'; import { Cuaderno } from './cuaderno'; import { CuadernoOng } from '../cuaderno/cuaderno-ong/cuaderno-ong'; import { CuadernoMision } from '../...
{ static routes = ROUTER_CONFIG; }
CuadernoModule
identifier_name
index.ts
import { CommonModule } from '@angular/common' import { RouterModule } from '@angular/router'; import { NgModule } from '@angular/core'; import AsesorModule from '../asesor'; import { Cuaderno } from './cuaderno'; import { CuadernoOng } from '../cuaderno/cuaderno-ong/cuaderno-ong'; import { CuadernoMision } from '../...
], imports: [ RouterModule.forChild(ROUTER_CONFIG), CommonModule, AsesorModule ] }) export default class CuadernoModule { static routes = ROUTER_CONFIG; }
CuadernoMatriz, CuadernoOprenar
random_line_split
validate.py
__author__ = 'sam' import webargs from .string import lowercase, strip def not_null(value): """A validation function that checks that a value isn't None.""" return True if value is not None else False def not_empty(value): """ Check if a value is not empty. This is a simple check that blocks n...
`min` and `max` cannot both be None. :param min: A lower bound for the value. Optional. :param max: An upper bound for the value. Optional. :return: A validation function """ if min is None and max is None: raise ValueError("A min or max value must be specified") def validate_withi...
random_line_split
validate.py
__author__ = 'sam' import webargs from .string import lowercase, strip def not_null(value): """A validation function that checks that a value isn't None.""" return True if value is not None else False def not_empty(value): """ Check if a value is not empty. This is a simple check that blocks n...
raise webargs.ValidationError( "Invalid value %s. Valid choices are %s" % (repr(value), repr(valid_choices))) return validate_choices def within(min=None, max=None): """ Create a validation function to check whether an argument value is within a specified ...
""" Create a validation function that will ensure a value is in a list of choices. A usage example: ``Arg(validate=choices(["foo", "bar"])) :param valid_choices: A list of valid values for this parameter :param case_sensitive: If false, any string-like values will be lowercased befor...
identifier_body
validate.py
__author__ = 'sam' import webargs from .string import lowercase, strip def not_null(value): """A validation function that checks that a value isn't None.""" return True if value is not None else False def not_empty(value): """ Check if a value is not empty. This is a simple check that blocks n...
if value in valid_choices: return True else: raise webargs.ValidationError( "Invalid value %s. Valid choices are %s" % (repr(value), repr(valid_choices))) return validate_choices def within(min=None, max=None): """ Create a validati...
value = lowercase(value)
conditional_block
validate.py
__author__ = 'sam' import webargs from .string import lowercase, strip def not_null(value): """A validation function that checks that a value isn't None.""" return True if value is not None else False def not_empty(value): """ Check if a value is not empty. This is a simple check that blocks n...
(min=None, max=None): """ Create a validation function to check whether an argument value is within a specified range (inclusive). `min` and `max` cannot both be None. :param min: A lower bound for the value. Optional. :param max: An upper bound for the value. Optional. :return: A validatio...
within
identifier_name
renderer.rs
use glium; use glium::index::PrimitiveType::*; use glium::texture::*; use glium::uniforms::*; use glium::*; use glutin::dpi::*; use glutin::*; use image::{load_from_memory_with_format, ImageFormat}; use runic::default_program; use resources::TILESET; use settings::Settings; const TITLE: &str = "War Against Machines";...
{ pub src: [f32; 4], pub overlay_colour: [f32; 4], pub dest: [f32; 2], pub rotation: f32, pub scale: f32, } struct Uniforms { screen_resolution: [f32; 2], tileset_size: [f32; 2], texture: SrgbTexture2d, } pub struct Renderer { uniforms: Uniforms, pub target: Frame, pub dis...
Properties
identifier_name
renderer.rs
use glium; use glium::index::PrimitiveType::*; use glium::texture::*; use glium::uniforms::*; use glium::*; use glutin::dpi::*; use glutin::*; use image::{load_from_memory_with_format, ImageFormat}; use runic::default_program; use resources::TILESET; use settings::Settings; const TITLE: &str = "War Against Machines";...
// Create the context and display let context = ContextBuilder::new().with_vsync(true); let display = Display::new(builder, context, &event_loop).unwrap(); // Create the buffers and program let vertex_buffer = VertexBuffer::new(&display, SQUARE).unwrap(); let indices =...
{ builder = builder.with_fullscreen(Some(event_loop.get_primary_monitor())); }
conditional_block
renderer.rs
use glium; use glium::index::PrimitiveType::*; use glium::texture::*; use glium::uniforms::*; use glium::*; use glutin::dpi::*; use glutin::*; use image::{load_from_memory_with_format, ImageFormat}; use runic::default_program; use resources::TILESET; use settings::Settings; const TITLE: &str = "War Against Machines";...
// Set the window to be fullscreen if that's set in settings if settings.fullscreen { builder = builder.with_fullscreen(Some(event_loop.get_primary_monitor())); } // Create the context and display let context = ContextBuilder::new().with_vsync(true); let dis...
.with_title(TITLE) .with_dimensions(LogicalSize::new(f64::from(width), f64::from(height)));
random_line_split
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
def search_events(self, query): with self.browser: if CATEGORIES.CINE in query.categories: if query.city and re.match('\d{5}', query.city): events = list(self.browser.search_events(query)) events.sort(key=lambda x: x.start_date, reverse=False...
ollection.path_level == 0: return if collection.path_level == 1 and (collection.basename in [u'comingsoon', u'nowshowing', u'acshow', u'interview']): return if collection.path_level == 2 and collection.parent_path == [u'acshow']: ...
identifier_body
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
self, id, country=None): return self.browser.get_movie_releases(id, country) def fill_person(self, person, fields): if 'real_name' in fields or 'birth_place' in fields\ or 'death_date' in fields or 'nationality' in fields\ or 'short_biography' in fields or 'roles' in fields\...
et_movie_releases(
identifier_name
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
for video in videos: yield video if collection.path_level == 2: videos = self.browser.get_categories_videos(':'.join(collection.split_path)) if videos: for video in videos: ...
ollection = self.get_collection(objs, split_path) if collection.path_level == 0: yield Collection([u'comingsoon'], u'Films prochainement au cinéma') yield Collection([u'nowshowing'], u'Films au cinéma') yield Collection([u'acshow'], u'Émissions...
conditional_block
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
with self.browser: split_id = _id.split('#') if split_id[-1] == 'movie': return self.browser.get_movie_from_id(split_id[0]) return self.browser.get_video_from_id(split_id[0], split_id[-1]) def iter_resources(self, objs, split_path): with self.brow...
video.thumbnail.data = self.browser.readurl(video.thumbnail.url) return video def get_video(self, _id):
random_line_split
colors.py
""" Zoolander's color handling module. """ import operator class HexMetaClass(type): OPERATORS = ("add", "sub", "mul", "div") def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) def overload(op): """ Overload this operator with a function ...
(self, other): my_class = type(self) op_fn = getattr(operator, op) if isinstance(other, my_class): return my_class(hex(op_fn(self.num, other.num))) elif isinstance(other, int) or isinstance(other, float): return my_c...
overloaded_fn
identifier_name
colors.py
""" Zoolander's color handling module. """ import operator class HexMetaClass(type): OPERATORS = ("add", "sub", "mul", "div") def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) def overload(op): """ Overload this operator with a function ...
def __str__(self): return "#%s" % hex(self.num).replace("0x", "")
random_line_split
colors.py
""" Zoolander's color handling module. """ import operator class HexMetaClass(type): OPERATORS = ("add", "sub", "mul", "div") def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) def overload(op): """ Overload this operator with a function ...
elif isinstance(other, int) or isinstance(other, float): return my_class(hex(op_fn(self.num, other))) elif isinstance(other, str): return my_class(hex(self.num + int(other, 16))) else: raise TypeError("Unsupport...
return my_class(hex(op_fn(self.num, other.num)))
conditional_block
colors.py
""" Zoolander's color handling module. """ import operator class HexMetaClass(type): OPERATORS = ("add", "sub", "mul", "div") def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) def overload(op): """ Overload this operator with a function ...
return overloaded_fn for op in mcs.OPERATORS: setattr(cls, "__%s__" % op, overload(op)) setattr(cls, "__r%s__" % op, "__%s__" % op) return cls class Hex(object): __metaclass__ = HexMetaClass def __init__(self, hex_string): if hex_string[0] == "#":...
my_class = type(self) op_fn = getattr(operator, op) if isinstance(other, my_class): return my_class(hex(op_fn(self.num, other.num))) elif isinstance(other, int) or isinstance(other, float): return my_class(hex(op_fn(self.num, other)...
identifier_body
constants.ts
export module AreaCodes { export const PUBLISHRESULTS = 'PublishResults';
export const RUNTESTSLOCALLY = 'RunTestsLocally'; export const INVALIDSETTINGSFILE = 'InvalidSettingsFile'; export const EXECUTEVSTEST = 'ExecuteVsTest'; export const GETVSTESTTESTSLISTINTERNAL = 'GetVsTestTestsListInternal'; export const UPDATERESPONSEFILE = 'UpdateResponseFile'; export const R...
export const INVOKEVSTEST = 'InvokeVsTest';
random_line_split
conv2n.rs
use crate::{convolve2n, convolve3}; use mli::*; use mli_ndarray::Ndeep; use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr}; use std::marker::PhantomData; type D2 = ndarray::Ix2; type D3 = ndarray::Ix3; #[derive(Clone, Debug)] pub struct Conv2n<S>(Array3<f32>, PhantomData<S>); impl<S> Conv2n<S>...
// If the filter is 1 in either dimension, the below code wont work. if filter_dims.0 <= 1 || filter_dims.1 <= 1 { unimplemented!("mli-conv: filter dimensions of 1 not implemented yet"); } let padding = (2 * (filter_dims.0 - 1), 2 * (filter_dims.1 - 1)); let pad_dims ...
random_line_split
conv2n.rs
use crate::{convolve2n, convolve3}; use mli::*; use mli_ndarray::Ndeep; use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr}; use std::marker::PhantomData; type D2 = ndarray::Ix2; type D3 = ndarray::Ix3; #[derive(Clone, Debug)] pub struct Conv2n<S>(Array3<f32>, PhantomData<S>); impl<S> Conv2n<S>...
(filters: Array3<f32>) -> Self { Self(filters, PhantomData) } } impl<S> Forward for Conv2n<S> where S: Data<Elem = f32>, { type Input = ArrayBase<S, D2>; type Internal = (); type Output = Array3<f32>; fn forward(&self, input: &Self::Input) -> ((), Self::Output) { let Self(filte...
new
identifier_name
conv2n.rs
use crate::{convolve2n, convolve3}; use mli::*; use mli_ndarray::Ndeep; use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr}; use std::marker::PhantomData; type D2 = ndarray::Ix2; type D3 = ndarray::Ix3; #[derive(Clone, Debug)] pub struct Conv2n<S>(Array3<f32>, PhantomData<S>); impl<S> Conv2n<S>...
let padding = (2 * (filter_dims.0 - 1), 2 * (filter_dims.1 - 1)); let pad_dims = ( output_delta.shape()[0], output_delta.shape()[1] + padding.0, output_delta.shape()[2] + padding.1, ); let mut pad = Array::zeros(pad_dims); #[allow(clippy::dere...
{ unimplemented!("mli-conv: filter dimensions of 1 not implemented yet"); }
conditional_block
conv2n.rs
use crate::{convolve2n, convolve3}; use mli::*; use mli_ndarray::Ndeep; use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr}; use std::marker::PhantomData; type D2 = ndarray::Ix2; type D3 = ndarray::Ix3; #[derive(Clone, Debug)] pub struct Conv2n<S>(Array3<f32>, PhantomData<S>); impl<S> Conv2n<S>...
} impl<S> Backward for Conv2n<S> where S: Data<Elem = f32>, { type OutputDelta = Array3<f32>; type InputDelta = Array2<f32>; type TrainDelta = Ndeep<OwnedRepr<f32>, D3>; fn backward( &self, input: &Self::Input, _: &Self::Internal, output_delta: &Self::OutputDelta, ...
{ let Self(filter, _) = self; ((), convolve2n(input.view(), filter.view())) }
identifier_body
CofenseTriageThreatEnrichment.py
from CommonServerPython import * ''' STANDALONE FUNCTION ''' def get_threat_indicator_list(args: Dict[str, Any]) -> list: """ Executes cofense-threat-indicator-list command for given arguments. :type args: ``Dict[str, Any]`` :param args: The script arguments provided by the user. :return: List ...
''' ENTRY POINT ''' if __name__ in ('__main__', '__builtin__', 'builtins'): main()
try: return_results(get_threat_indicator_list(demisto.args())) except Exception as e: demisto.error(traceback.format_exc()) # print the traceback return_error(f'Failed to execute CofenseTriageThreatEnrichment. Error: {str(e)}')
identifier_body
CofenseTriageThreatEnrichment.py
from CommonServerPython import * ''' STANDALONE FUNCTION ''' def get_threat_indicator_list(args: Dict[str, Any]) -> list: """ Executes cofense-threat-indicator-list command for given arguments. :type args: ``Dict[str, Any]`` :param args: The script arguments provided by the user. :return: List ...
main()
conditional_block
CofenseTriageThreatEnrichment.py
from CommonServerPython import * ''' STANDALONE FUNCTION ''' def
(args: Dict[str, Any]) -> list: """ Executes cofense-threat-indicator-list command for given arguments. :type args: ``Dict[str, Any]`` :param args: The script arguments provided by the user. :return: List of responses. :rtype: ``list`` """ # Fetch threat indicators based on threat val...
get_threat_indicator_list
identifier_name
CofenseTriageThreatEnrichment.py
from CommonServerPython import * ''' STANDALONE FUNCTION ''' def get_threat_indicator_list(args: Dict[str, Any]) -> list: """ Executes cofense-threat-indicator-list command for given arguments. :type args: ``Dict[str, Any]`` :param args: The script arguments provided by the user. :return: List ...
return_error(f'Failed to execute CofenseTriageThreatEnrichment. Error: {str(e)}') ''' ENTRY POINT ''' if __name__ in ('__main__', '__builtin__', 'builtins'): main()
demisto.error(traceback.format_exc()) # print the traceback
random_line_split
recipe.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, URLSearchParams, Response, RequestOptions } from '@angular/http'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { environment } from '../../environments/environment'; import { User, Recipe } from '../_models/index'; // import { Obse...
getRecipeById(recipeID: string): Observable<Recipe>{ let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', `${this.token}`); return this.http.get(this.urlGetRecipeByID+"/"+recipeID, { headers, search: "none yet", }) .map((...
// console.error(errMsg); // log to console instead return Observable.throw(errMsg); }); };
random_line_split
recipe.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, URLSearchParams, Response, RequestOptions } from '@angular/http'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { environment } from '../../environments/environment'; import { User, Recipe } from '../_models/index'; // import { Obse...
(recipeID: string): Observable<Recipe>{ let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', `${this.token}`); return this.http.get(this.urlGetRecipeByID+"/"+recipeID, { headers, search: "none yet", }) .map((response: Response)...
getRecipeById
identifier_name
stock_picking.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
(models.Model): _inherit = 'stock.picking' carrier_price = fields.Float(string="Shipping Cost", readonly=True) delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True) @api.multi def do_transfer(self): res = super(StockPicking, self).do_transfer() if sel...
StockPicking
identifier_name
stock_picking.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
# No carrier if not carrier: return None # Carrier already invoiced on the sale order if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids): return None # Classic carrier if carrier.delivery_type == 'grid...
random_line_split
stock_picking.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
if not account_id: account_id = carrier.product_id.categ_id.property_account_income_categ.id taxes = carrier.product_id.taxes_id taxes_ids = taxes.ids # Apply original SO fiscal position if picking.sale_id.fiscal_position_id: fpos = picking.sale_id.fisca...
picking.ensure_one() invoice.ensure_one() carrier = picking.carrier_id # No carrier if not carrier: return None # Carrier already invoiced on the sale order if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids): ...
identifier_body
stock_picking.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
# Shipping provider price = picking.carrier_price account_id = carrier.product_id.property_account_income.id if not account_id: account_id = carrier.product_id.categ_id.property_account_income_categ.id taxes = carrier.product_id.taxes_id taxes_ids = taxes....
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
conditional_block
blocking.rs
//! //! A demonstration of constructing and using a blocking stream. //! //! Audio from the default input device is passed directly to the default output device in a duplex //! stream, so beware of feedback! //! extern crate portaudio; use portaudio::pa; use std::error::Error; use std::mem::replace; const SAMPLE_RAT...
() { println!("PortAudio version : {}", pa::get_version()); println!("PortAudio version text : {}", pa::get_version_text()); match pa::initialize() { Ok(()) => println!("Successfully initialized PortAudio"), Err(err) => println!("An error occurred while initializing PortAudio: {}", err.des...
main
identifier_name
blocking.rs
//! //! A demonstration of constructing and using a blocking stream. //! //! Audio from the default input device is passed directly to the default output device in a duplex //! stream, so beware of feedback! //! extern crate portaudio; use portaudio::pa; use std::error::Error; use std::mem::replace; const SAMPLE_RAT...
let def_input = pa::device::get_default_input(); let input_info = match pa::device::get_info(def_input) { Ok(info) => info, Err(err) => panic!("An error occurred while retrieving input info: {}", err.description()), }; println!("Default input device info :"); println!("\tversion : {}...
{ println!("PortAudio version : {}", pa::get_version()); println!("PortAudio version text : {}", pa::get_version_text()); match pa::initialize() { Ok(()) => println!("Successfully initialized PortAudio"), Err(err) => println!("An error occurred while initializing PortAudio: {}", err.descri...
identifier_body
blocking.rs
//! //! A demonstration of constructing and using a blocking stream. //! //! Audio from the default input device is passed directly to the default output device in a duplex //! stream, so beware of feedback! //! extern crate portaudio;
use std::error::Error; use std::mem::replace; const SAMPLE_RATE: f64 = 44_100.0; const CHANNELS: u32 = 2; const FRAMES: u32 = 256; fn main() { println!("PortAudio version : {}", pa::get_version()); println!("PortAudio version text : {}", pa::get_version_text()); match pa::initialize() { Ok(()) =...
use portaudio::pa;
random_line_split
child.js
/** * @file child.js * Colorbox Modal iframe pages' JS */ (function($) { /** * Colorbox Modal object for child windows. */ Drupal.cbmodal_child = Drupal.cbmodal_child || { processed: false, behaviors: {} }; /** * Child modal behavior. */ Drupal.cbmodal_child.attach = function(context...
*/ Drupal.behaviors.cbmodal_child = {}; Drupal.behaviors.cbmodal_child.attach = function (context, settings) { Drupal.cbmodal_child.attach(context); } })(jQuery);
* problems with other behaviors that need the document visible in order to * do its own job.
random_line_split
child.js
/** * @file child.js * Colorbox Modal iframe pages' JS */ (function($) { /** * Colorbox Modal object for child windows. */ Drupal.cbmodal_child = Drupal.cbmodal_child || { processed: false, behaviors: {} }; /** * Child modal behavior. */ Drupal.cbmodal_child.attach = function(contex...
$(this).attr('target', '_blank'); }); }; /** * Set iframe scrollbar visibility * Only display scrollbar if parent browser viewport height is enough * Hacky : if any interaction inside iframe changes the height, no way to scroll anymore... */ Drupal.cbmodal_child.behaviors.RemoveIframeScrol...
{ return; }
conditional_block
bootstrap-table-uk-UA.min.js
/* * bootstrap-table - v1.8.1 - 2015-05-29 * https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2015 zhixin wen * Licensed MIT License */ !function(a){"use strict";a.fn.bootstrapTable.locales["uk-UA"]={formatLoadingMessage:function(){return"Завантаження, будь ласка, зачекайте..."},formatRecordsPerPage:function(a){return a+" записів на сторінку"},formatShowingRows:function(a,b,c){return"Показано з ...
random_line_split
photo-gallery.tsx
import React from "react"; import Gallery, { PhotoProps } from "react-photo-gallery"; import * as styles from "./photo-gallery.module.css"; interface PhotoGalleryProps { photos: Array<PhotoProps<any>>; } interface PhotoGalleryState { images: Array<PhotoProps<any>>; lightbox?: IGlightbox; } export default class...
}; override render = () => { return ( <section className={styles.photoGallery}> <Gallery photos={this.state.images} onClick={this.openLightbox} /> </section> ); }; }
{ this.state.lightbox?.openAt(at.index); }
conditional_block
photo-gallery.tsx
import React from "react"; import Gallery, { PhotoProps } from "react-photo-gallery"; import * as styles from "./photo-gallery.module.css"; interface PhotoGalleryProps { photos: Array<PhotoProps<any>>; } interface PhotoGalleryState { images: Array<PhotoProps<any>>; lightbox?: IGlightbox; } export default class...
(props: PhotoGalleryProps) { super(props); this.state = { images: props.photos, }; } openLightbox = (_: any, at: { index: number }) => { if (!this.state.lightbox) { const Glightbox = require("glightbox"); this.setState( { ...this.state, lightbox: Glight...
constructor
identifier_name
photo-gallery.tsx
import React from "react"; import Gallery, { PhotoProps } from "react-photo-gallery"; import * as styles from "./photo-gallery.module.css"; interface PhotoGalleryProps { photos: Array<PhotoProps<any>>; } interface PhotoGalleryState { images: Array<PhotoProps<any>>; lightbox?: IGlightbox; } export default class...
openLightbox = (_: any, at: { index: number }) => { if (!this.state.lightbox) { const Glightbox = require("glightbox"); this.setState( { ...this.state, lightbox: Glightbox({ elements: this.state.images.map((i) => { i.href = i.src; r...
{ super(props); this.state = { images: props.photos, }; }
identifier_body
photo-gallery.tsx
import React from "react"; import Gallery, { PhotoProps } from "react-photo-gallery"; import * as styles from "./photo-gallery.module.css"; interface PhotoGalleryProps { photos: Array<PhotoProps<any>>; } interface PhotoGalleryState { images: Array<PhotoProps<any>>; lightbox?: IGlightbox; } export default class...
override render = () => { return ( <section className={styles.photoGallery}> <Gallery photos={this.state.images} onClick={this.openLightbox} /> </section> ); }; }
} else { this.state.lightbox?.openAt(at.index); } };
random_line_split
handler_storage.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::sync::{Arc, RwLock}; use std::error::Error; use rustful::{ Server, Context, Response, Handler, TreeRouter, StatusCode }; use rustful::file::{self, Loader}; fn main() { println!("...
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> { //Read file into a string let mut string = String::new(); File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string) } enum Api { Counter { //We are using the handler to preload the page in this exmaple ...
{ value - 1 }
identifier_body
handler_storage.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::sync::{Arc, RwLock}; use std::error::Error; use rustful::{ Server, Context, Response, Handler, TreeRouter, StatusCode }; use rustful::file::{self, Loader}; fn main() { println!("...
//Insert the value into the page and write it to the response let count = value.read().unwrap().to_string(); response.send(page.replace("{}", &count[..])); }, Api::File => { if let Some(file) = context.variables.get("file") { ...
*value = op(*value); });
random_line_split
handler_storage.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::sync::{Arc, RwLock}; use std::error::Error; use rustful::{ Server, Context, Response, Handler, TreeRouter, StatusCode }; use rustful::file::{self, Loader}; fn main() { println!("...
(value: i32) -> i32 { value - 1 } fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> { //Read file into a string let mut string = String::new(); File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string) } enum Api { Counter { //We are using the handler to...
sub
identifier_name
handler_storage.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::sync::{Arc, RwLock}; use std::error::Error; use rustful::{ Server, Context, Response, Handler, TreeRouter, StatusCode }; use rustful::file::{self, Loader}; fn main() { println!("...
else { //Something went horribly wrong context.log.error(&format!("failed to open '{}': {}", file, e.description())); response.set_status(StatusCode::InternalServerError); } } ...
{ response.set_status(StatusCode::NotFound); }
conditional_block
126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py
# $Id: 126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py 369517 2012-07-01 17:28:57Z file $ import inc_sip as sip import inc_sdp as sdp sdp = \ """ v=0 o=- 0 0 IN IP4 127.0.0.1 s=- c=IN IP4 127.0.0.1
m=audio 5000 RTP/AVP 0 """ pjsua_args = "--null-audio --auto-answer 200" extra_headers = "" include = ["Content-Type: application/sdp", # response must include SDP "m=video 0 RTP/AVP[\\s\\S]+m=audio [1-9]+[0-9]* RTP/AVP" ] exclude = [] sendto_cfg = sip.SendtoCfg("SDP media with port 0 and no rtpmap for dynami...
t=0 0 m=video 0 RTP/AVP 100
random_line_split
ITrigger.ts
import { IArtifact, IExecution, ITemplateInheritable } from 'core/domain'; export interface ITrigger extends ITemplateInheritable { artifacts?: IArtifact[]; description?: string; enabled: boolean; rebake?: boolean; user?: string; type: string;
export interface IArtifactoryTrigger extends ITrigger { artifactorySearchName: string; artifactoryRepository: string; type: 'artifactory'; } export interface INexusTrigger extends ITrigger { nexusSearchName: string; nexusRepository: string; type: 'nexus'; } export interface IDockerTrigger extends ITrigge...
expectedArtifactIds?: string[]; // uuid references to ExpectedArtifacts defined in the Pipeline. runAsUser?: string; excludedArtifactTypePatterns?: RegExp[]; }
random_line_split
index.js
/** * Copyright 2015 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 applic...
}], 'require-jsdoc': 1, 'max-len': [1, 80, 4, { ignoreComments: true, ignoreUrls: true }], // Resetting things that eslint-config-xo has an opinion about, but the // Google Style Guide doesn't. 'curly': 0, 'no-floating-decimal': 0, 'no-unused-vars': [2, { "args":...
requireReturn: false, prefer: { returns: 'return' }
random_line_split
bookmark.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
}
{ self.is::<IsBookmark>() }
identifier_body
bookmark.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
(&self) -> Result<bool> { self.is::<IsBookmark>() } }
is_bookmark
identifier_name
bookmark.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
}
self.is::<IsBookmark>() }
random_line_split
nicedit.js
(function($) { /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.nicedit = function(context, params, settings) { // Intercept and ignore submit handlers or they will revert changes made // since the instance was removed. The handlers are anonymous and hidden out // of scope ...
/** * Instance methods for nicEdit. */ Drupal.wysiwyg.editor.instance.nicedit = { insert: function (content) { var instance = nicEditors.findEditor(this.field), editingArea = instance.getElm(), sel = instance.getSel(), range; // IE. if (document.selection) { range = sel.creat...
{ var found = false; if (innerNode === outerNode) { return true; } $(innerNode).parents().each(function (index, parent) { if (parent === outerNode) { found = true; return false; } }); return found; }
identifier_body
nicedit.js
(function($) { /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.nicedit = function(context, params, settings) { // Intercept and ignore submit handlers or they will revert changes made // since the instance was removed. The handlers are anonymous and hidden out // of scope ...
(innerNode, outerNode) { var found = false; if (innerNode === outerNode) { return true; } $(innerNode).parents().each(function (index, parent) { if (parent === outerNode) { found = true; return false; } }); return found; } /** * Instance methods for nicEdit. */ D...
isInside
identifier_name
nicedit.js
(function($) { /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.nicedit = function(context, params, settings) { // Intercept and ignore submit handlers or they will revert changes made // since the instance was removed. The handlers are anonymous and hidden out // of scope ...
} else { // The code below doesn't work in IE, but it never gets here. // Convert selection to a range. // W3C compatible. if (sel.getRangeAt) { if (sel.rangeCount > 0) { range = sel.getRangeAt(0); } } // Safari. else { ...
{ // Insert content and set the caret after it. range.pasteHTML(content); range.select(); range.collapse(false); }
conditional_block
nicedit.js
(function($) { /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.nicedit = function(context, params, settings) { // Intercept and ignore submit handlers or they will revert changes made // since the instance was removed. The handlers are anonymous and hidden out // of scope ...
// If the caret is not in the editing area, just append the content. if (!isInside(range.parentElement(), editingArea)) { editingArea.innerHTML += content; } else { // Insert content and set the caret after it. range.pasteHTML(content); range.select(); ...
if (document.selection) { range = sel.createRange();
random_line_split
extern-crate-used.rs
// Extern crate items are marked as used if they are used
// edition:2018 #![deny(unused_extern_crates)] // Shouldn't suggest changing to `use`, as new name // would no longer be added to the prelude which could cause // compilation errors for imports that use the new name in // other modules. See #57672. extern crate core as iso1; extern crate core as iso2; extern crate co...
// through extern prelude entries introduced by them.
random_line_split
extern-crate-used.rs
// Extern crate items are marked as used if they are used // through extern prelude entries introduced by them. // edition:2018 #![deny(unused_extern_crates)] // Shouldn't suggest changing to `use`, as new name // would no longer be added to the prelude which could cause // compilation errors for imports that use th...
{}
identifier_body
extern-crate-used.rs
// Extern crate items are marked as used if they are used // through extern prelude entries introduced by them. // edition:2018 #![deny(unused_extern_crates)] // Shouldn't suggest changing to `use`, as new name // would no longer be added to the prelude which could cause // compilation errors for imports that use th...
() {}
main
identifier_name
__init__.py
#!/usr/bin/env pythonw import sys from os import path import pkg_resources command = path.split(sys.argv[0])[-1] from .program_envs import prog_env if command.endswith(".py"): mpl_env = prog_env.get(command[:-3]) elif command.endswith("_a"): mpl_env = prog_env.get(command[:-2]) else: mpl_env = prog_env.g...
#from . import generic_magic #from . import sio_magic #from . import cit_magic #from . import _2g_bin_magic #from . import huji_magic #from . import huji_magic_new #from . import ldeo_magic #from . import iodp_srm_magic #from . import iodp_dscr_magic #from . import iodp_samples_magic #from . import pmd_magic #from . ...
print("You are running:") try: print(pkg_resources.get_distribution('pmagpy')) except pkg_resources.DistributionNotFound: pass try: print(pkg_resources.get_distribution('pmagpy-cli')) except pkg_resources.DistributionNotFound: pass
conditional_block
__init__.py
#!/usr/bin/env pythonw import sys from os import path import pkg_resources command = path.split(sys.argv[0])[-1] from .program_envs import prog_env if command.endswith(".py"): mpl_env = prog_env.get(command[:-3]) elif command.endswith("_a"): mpl_env = prog_env.get(command[:-2]) else: mpl_env = prog_env.g...
matplotlib.use("TKAgg") if "-v" in sys.argv: print("You are running:") try: print(pkg_resources.get_distribution('pmagpy')) except pkg_resources.DistributionNotFound: pass try: print(pkg_resources.get_distribution('pmagpy-cli')) except pkg_resources.DistributionNotFo...
# if backend wasn't set yet, set it appropriately else: if mpl_env: matplotlib.use(mpl_env) else:
random_line_split
main.rs
#![deny(trivial_casts, trivial_numeric_casts)] extern crate byteorder; #[macro_use] extern crate clap; #[macro_use] extern crate enum_primitive; extern crate num; extern crate rand; extern crate sdl2; extern crate time; use std::fs::File; use std::io::Read; use clap::{Arg, App}; use vm::VM; mod cart;
mod interconnect; mod memory; mod mem_map; mod reg_status; mod vm; fn main() { let matches = App::new("NES Emulator") .version(crate_version!()) .author("tompko <tompko@gmail.com>") .about("Emulates the NES") .arg(Arg:...
mod cpu; mod graphics; mod input;
random_line_split
main.rs
#![deny(trivial_casts, trivial_numeric_casts)] extern crate byteorder; #[macro_use] extern crate clap; #[macro_use] extern crate enum_primitive; extern crate num; extern crate rand; extern crate sdl2; extern crate time; use std::fs::File; use std::io::Read; use clap::{Arg, App}; use vm::VM; mod cart; mod cpu; mod gr...
, Err(err) => { println!("nesRS: cannot open '{}': {}", filename, err); std::process::exit(-1); } } buffer.into_boxed_slice() }
{ file.read_to_end(&mut buffer).unwrap(); }
conditional_block
main.rs
#![deny(trivial_casts, trivial_numeric_casts)] extern crate byteorder; #[macro_use] extern crate clap; #[macro_use] extern crate enum_primitive; extern crate num; extern crate rand; extern crate sdl2; extern crate time; use std::fs::File; use std::io::Read; use clap::{Arg, App}; use vm::VM; mod cart; mod cpu; mod gr...
(filename: &str) -> Box<[u8]> { let mut buffer = Vec::new(); match File::open(filename) { Ok(ref mut file) => { file.read_to_end(&mut buffer).unwrap(); }, Err(err) => { println!("nesRS: cannot open '{}': {}", filename, err); std::process::exit(-1); ...
read_rom
identifier_name
main.rs
#![deny(trivial_casts, trivial_numeric_casts)] extern crate byteorder; #[macro_use] extern crate clap; #[macro_use] extern crate enum_primitive; extern crate num; extern crate rand; extern crate sdl2; extern crate time; use std::fs::File; use std::io::Read; use clap::{Arg, App}; use vm::VM; mod cart; mod cpu; mod gr...
{ let mut buffer = Vec::new(); match File::open(filename) { Ok(ref mut file) => { file.read_to_end(&mut buffer).unwrap(); }, Err(err) => { println!("nesRS: cannot open '{}': {}", filename, err); std::process::exit(-1); } } buffer.int...
identifier_body
normal_gamma.py
""" Normal-Gamma density.""" import numpy as np from scipy.special import gammaln, psi class NormalGamma(object): """Normal-Gamma density. Attributes ---------- mu : numpy.ndarray Mean of the Gaussian density. kappa : float Factor of the precision matrix. alpha : float ...
expLogPrecision() Expected value of the logarithm of the precision. expPrecision() Expected value of the precision. KL(self, pdf) KL divergence between the current and the given densities. newPosterior(self, stats) Create a new Normal-Gamma density. """ def __ini...
Methods -------
random_line_split
normal_gamma.py
""" Normal-Gamma density.""" import numpy as np from scipy.special import gammaln, psi class
(object): """Normal-Gamma density. Attributes ---------- mu : numpy.ndarray Mean of the Gaussian density. kappa : float Factor of the precision matrix. alpha : float Shape parameter of the Gamma density. beta : numpy.ndarray Rate parameters of the Gamma densi...
NormalGamma
identifier_name
normal_gamma.py
""" Normal-Gamma density.""" import numpy as np from scipy.special import gammaln, psi class NormalGamma(object): """Normal-Gamma density. Attributes ---------- mu : numpy.ndarray Mean of the Gaussian density. kappa : float Factor of the precision matrix. alpha : float ...
def expPrecision(self): """Expected value of the precision. Returns ------- E_prec : numpy.ndarray Precision. """ return self.alpha/self.beta def KL(self, q): """KL divergence between the current and the given densities. Returns ...
'''Expected value of the logarithm of the precision. Returns ------- E_log_prec : numpy.ndarray Log precision. ''' return psi(self.alpha) - np.log(self.beta)
identifier_body
api.test.js
import request from 'supertest'; import low from 'lowdb'; import apiLoader from '../src/api.js'; import Car from '../../models/Car.js'; const freshDB = () => { const fresh = low(); fresh.defaults({ cars: [] }).write(); return fresh; }; describe('GET /api/cars', () => { let db; let api; beforeEach(() => { ...
.set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars).toEqual([]); })); test('respond with cars that match criteria', () => { db.get('cars') .push(new Car('a', 'fox', 20000, 2013, 100000)) ...
test('respond with json', () => request(api) .get('/api/cars')
random_line_split
index.ts
import { CameraRoll as RNCameraRoll, NativeModules, Platform, } from 'react-native'; /** * @author 田尘殇Sean(sean.snow@live.com) * @date 2017/4/18 */ export default class Camera
** * Saves the photo or video to the camera roll / gallery. * * the tag can be any image URI (including local, remote asset-library and base64 data URIs) * or a local video file URI (remote or data URIs are not supported for saving video at this time). * * If the tag has a file extension of .mov or .m...
Roll { /
identifier_name
index.ts
import { CameraRoll as RNCameraRoll, NativeModules, Platform, } from 'react-native'; /** * @author 田尘殇Sean(sean.snow@live.com) * @date 2017/4/18 */ export default class CameraRoll { /** * Saves the photo or video to the camera roll / gallery. * * the tag can be any image URI (including local, remot...
eturn RNCameraRoll.saveToCameraRoll(tag, type); } }
return NativeModules.SitbCameraRollManager.saveToCameraRoll(tag, type); } r
conditional_block
index.ts
import { CameraRoll as RNCameraRoll, NativeModules, Platform, } from 'react-native'; /** * @author 田尘殇Sean(sean.snow@live.com) * @date 2017/4/18 */ export default class CameraRoll { /** * Saves the photo or video to the camera roll / gallery. * * the tag can be any image URI (including local, remot...
if (Platform.OS === 'android') { return NativeModules.SitbCameraRollManager.saveToCameraRoll(tag, type); } return RNCameraRoll.saveToCameraRoll(tag, type); } }
identifier_body
index.ts
import { CameraRoll as RNCameraRoll, NativeModules, Platform, } from 'react-native'; /** * @author 田尘殇Sean(sean.snow@live.com) * @date 2017/4/18 */ export default class CameraRoll { /** * Saves the photo or video to the camera roll / gallery. * * the tag can be any image URI (including local, remot...
return RNCameraRoll.saveToCameraRoll(tag, type); } }
}
random_line_split
043_migrate_template_versions.py
# 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 # d...
(migrate_engine): Session = sessionmaker(bind=migrate_engine) session = Session() meta = sqlalchemy.MetaData(bind=migrate_engine) templ_table = sqlalchemy.Table('raw_template', meta, autoload=True) raw_templates = templ_table.select().execute() # NOTE (sdake) 2014-04-24 is the date of the Ice...
upgrade
identifier_name
043_migrate_template_versions.py
# 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 # d...
import time from oslo_serialization import jsonutils import sqlalchemy from sqlalchemy.orm import sessionmaker def upgrade(migrate_engine): Session = sessionmaker(bind=migrate_engine) session = Session() meta = sqlalchemy.MetaData(bind=migrate_engine) templ_table = sqlalchemy.Table('raw_template',...
random_line_split
043_migrate_template_versions.py
# 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 # d...
session.close()
template[key] = date (templ_table.update(). where(templ_table.c.id == raw_template.id). values(template=jsonutils.dumps(template)). execute()) session.commit()
conditional_block
043_migrate_template_versions.py
# 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 # d...
template = jsonutils.loads(raw_template.template) if key in template: version = template[key] try: dt = time.strptime(version, '%Y-%m-%d') except (TypeError, ValueError): dt = None if dt is ...
Session = sessionmaker(bind=migrate_engine) session = Session() meta = sqlalchemy.MetaData(bind=migrate_engine) templ_table = sqlalchemy.Table('raw_template', meta, autoload=True) raw_templates = templ_table.select().execute() # NOTE (sdake) 2014-04-24 is the date of the Icehouse release. It is ...
identifier_body
log_settings.py
# coding=utf-8 """ https://docs.python.org/3/howto/logging.html https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ """ import logging import logging.config from logging import Formatter import pathlib import yaml import time from common.settings import AlgoSettings def setup_logging(default_lev...
(Formatter): converter = time.gmtime def log_title(msg): """Format for log titles :param msg: :return: """ total_len = 120 len_msg = len(msg) sides_space = (total_len-len_msg) - 2 l_space = sides_space / 2 r_space = l_space if sides_space % 2 != 0: r_space += 1 ...
UTCFormatter
identifier_name
log_settings.py
# coding=utf-8 """ https://docs.python.org/3/howto/logging.html https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ """ import logging import logging.config from logging import Formatter import pathlib import yaml import time from common.settings import AlgoSettings def setup_logging(default_lev...
l_str = int(l_space) * " " r_str = int(r_space) * " " complete_line = ('#' * total_len) msg_line = ('#' + l_str + msg + r_str + '#') space_line = "#" + (" " * (total_len - 2)) + "#" logging.info(complete_line) logging.info(space_line) logging.info(msg_line) logging.info(space_lin...
r_space += 1
conditional_block
log_settings.py
# coding=utf-8 """ https://docs.python.org/3/howto/logging.html https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ """ import logging import logging.config from logging import Formatter import pathlib import yaml import time from common.settings import AlgoSettings def setup_logging(default_lev...
class UTCFormatter(Formatter): converter = time.gmtime def log_title(msg): """Format for log titles :param msg: :return: """ total_len = 120 len_msg = len(msg) sides_space = (total_len-len_msg) - 2 l_space = sides_space / 2 r_space = l_space if sides_space % 2 != 0: ...
"""Update the logging configuration file with the paths defined in the CONFIG file """ sett = AlgoSettings() saving_path = pathlib.Path(sett.log_saving_path()) config_file = pathlib.Path(sett.log_configuration()) with open(config_file) as my_file: doc = yaml.load(my_file) doc['hand...
identifier_body
log_settings.py
# coding=utf-8 """ https://docs.python.org/3/howto/logging.html https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ """ import logging import logging.config from logging import Formatter import pathlib import yaml import time from common.settings import AlgoSettings def setup_logging(default_lev...
def log_title(msg): """Format for log titles :param msg: :return: """ total_len = 120 len_msg = len(msg) sides_space = (total_len-len_msg) - 2 l_space = sides_space / 2 r_space = l_space if sides_space % 2 != 0: r_space += 1 l_str = int(l_space) * " " r_str = ...
random_line_split
jquery.squeezebox.js
// sequential pairs of header/panel elements, and options // is an optional object with any of the following properties: // // activeHeaderClass: Class name to apply to the active header // headerSelector: Selector for the header elements // nextPanelSelector: Selector for the next panel from a header // speed: ...
// Replacement for jquery.ui.accordion to avoid dealing with // jquery.ui theming. // // Usage: $('#container').squeezebox(options); // where the direct child elements of '#container' are
random_line_split
jquery.squeezebox.js
// Replacement for jquery.ui.accordion to avoid dealing with // jquery.ui theming. // // Usage: $('#container').squeezebox(options); // where the direct child elements of '#container' are // sequential pairs of header/panel elements, and options // is an optional object with any of the following properties: // // ac...
else { panel.slideUp(options.speed); $(header).removeClass(options.activeHeaderClass); } }); }); }; })(jQuery);
{ panel.slideDown(options.speed); $(header).addClass(options.activeHeaderClass); }
conditional_block
base_class.py
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.de...
class TradfriBaseClass(Entity): """Base class for IKEA TRADFRI. All devices and groups should ultimately inherit from this class. """ _attr_should_poll = False def __init__( self, device: Device, api: Callable[[Command | list[Command]], Any], gateway_id: str, )...
return wrapper
random_line_split
base_class.py
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.de...
try: cmd = self._device.observe( callback=self._observe_update, err_callback=self._async_start_observe, duration=0, ) self.hass.async_create_task(self._api(cmd)) except PytradfriError as err: _LOGGER.warnin...
self.async_write_ha_state() _LOGGER.warning("Observation failed for %s", self._attr_name, exc_info=exc)
conditional_block
base_class.py
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.de...
(Entity): """Base class for IKEA TRADFRI. All devices and groups should ultimately inherit from this class. """ _attr_should_poll = False def __init__( self, device: Device, api: Callable[[Command | list[Command]], Any], gateway_id: str, ) -> None: """I...
TradfriBaseClass
identifier_name
base_class.py
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.de...
class TradfriBaseClass(Entity): """Base class for IKEA TRADFRI. All devices and groups should ultimately inherit from this class. """ _attr_should_poll = False def __init__( self, device: Device, api: Callable[[Command | list[Command]], Any], gateway_id: str, ...
"""Handle tradfri api call error.""" @wraps(func) async def wrapper(command: Command | list[Command]) -> None: """Decorate api call.""" try: await func(command) except PytradfriError as err: _LOGGER.error("Unable to execute command %s: %s", command, err) ret...
identifier_body
gdb-pretty-struct-and-enums-pre-gdb-7-7.rs
// Copyright 2013-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-MI...
}; let empty_struct = EmptyStruct; let c_style_enum1 = CStyleEnumVar1; let c_style_enum2 = CStyleEnumVar2; let c_style_enum3 = CStyleEnumVar3; zzz(); } fn zzz() { () }
random_line_split
gdb-pretty-struct-and-enums-pre-gdb-7-7.rs
// Copyright 2013-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-MI...
{ CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3, } fn main() { let regular_struct = RegularStruct { the_first_field: 101, the_second_field: 102.5, the_third_field: false }; let empty_struct = EmptyStruct; let c_style_enum1 = CStyleEnumVar1; let c_style_enum2...
CStyleEnum
identifier_name
persistence_promise.d.ts
export declare type FulfilledHandler<T, R> = ((result: T) => R | PersistencePromise<R>) | null; export declare type RejectedHandler<R> = ((reason: Error) => R | PersistencePromise<R>) | null; export declare type Resolver<T> = (value?: T) => void; export declare type Rejector = (error: Error) => void; /** * Persis...
* NOTE: .then() and .catch() only allow a single consumer, unlike normal * Promises. */ export declare class PersistencePromise<T> { private nextCallback; private catchCallback; private result; private error; private isDone; private callbackAttached; constructor(callback: (resol...
* commit transactions if control is returned to the event loop without * synchronously initiating another operation on the transaction. *
random_line_split
persistence_promise.d.ts
export declare type FulfilledHandler<T, R> = ((result: T) => R | PersistencePromise<R>) | null; export declare type RejectedHandler<R> = ((reason: Error) => R | PersistencePromise<R>) | null; export declare type Resolver<T> = (value?: T) => void; export declare type Rejector = (error: Error) => void; /** * Persis...
<T> { private nextCallback; private catchCallback; private result; private error; private isDone; private callbackAttached; constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void); catch<R>(fn: (error: Error) => R | PersistencePromise<R>): PersistencePromise<R>; ...
PersistencePromise
identifier_name
test_getlimits.py
""" Test functions for limits module. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble from numpy.testing import ( TestCase, run_module_suite, assert_equal, assert_ ) from numpy.core.getli...
ftype2 = finfo(float) assert_equal(id(ftype), id(ftype2)) class TestHalf(TestCase): def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) assert_equal(id(ftype), id(ftype2)) class TestSingle(TestCase): def test_singleton(self): ftype = finfo(single)...
random_line_split
test_getlimits.py
""" Test functions for limits module. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble from numpy.testing import ( TestCase, run_module_suite, assert_equal, assert_ ) from numpy.core.getli...
self.assertRaises(ValueError, finfo, 'i4') class TestIinfo(TestCase): def test_basic(self): dts = list(zip(['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'], [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64])) ...
for attr in ('bits', 'eps', 'epsneg', 'iexp', 'machar', 'machep', 'max', 'maxexp', 'min', 'minexp', 'negep', 'nexp', 'nmant', 'precision', 'resolution', 'tiny'): assert_equal(getattr(finfo(dt1), attr), getattr(finfo(dt2), att...
conditional_block
test_getlimits.py
""" Test functions for limits module. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble from numpy.testing import ( TestCase, run_module_suite, assert_equal, assert_ ) from numpy.core.getli...
(TestCase): def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) assert_equal(id(ftype), id(ftype2)) class TestSingle(TestCase): def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) assert_equal(id(ftype), id(ftype2)) class TestDo...
TestHalf
identifier_name