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
restrictederrorinfo.rs
// Copyright © 2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modi...
interface IRestrictedErrorInfo(IRestrictedErrorInfoVtbl): IUnknown(IUnknownVtbl) { fn GetErrorDetails( description: *mut ::BSTR, error: *mut ::HRESULT, restrictedDescription: *mut ::BSTR, capabilitySid: *mut ::BSTR, ) -> ::HRESULT, fn GetReference( reference: *mut ::B...
// except according to those terms. RIDL!( #[uuid(0x82ba7092, 0x4c88, 0x427d, 0xa7, 0xbc, 0x16, 0xdd, 0x93, 0xfe, 0xb6, 0x7e)]
random_line_split
update-hue-ini.py
## update-hue-ini.py ## ## This script will extract the appropriate IBM Analytics for Apache Hadoop credentials from the VCAP_SERVICES ## environment variable inside a running container. It will add the username and password to the hue.ini file ## so that the hue application has access to a specific instance import s...
if (username is not None and password is not None and webhdfsurl is not None): filedata = None with open (srcfile,'r') as file: filedata = file.read() filedata = filedata.replace('%instance_user%', username) filedata = filedata.replace('%instance_user_password%', password) filedata = filedata.repl...
random_line_split
update-hue-ini.py
## update-hue-ini.py ## ## This script will extract the appropriate IBM Analytics for Apache Hadoop credentials from the VCAP_SERVICES ## environment variable inside a running container. It will add the username and password to the hue.ini file ## so that the hue application has access to a specific instance import s...
if webhdfsurl is None: sys.stderr.write('URL endpoint missing\n') sys.exit(1)
sys.stderr.write('password missing\n')
conditional_block
std.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! # The Rust standard library The Rust standard library is a group of interrelated modules defining the core language traits, operations on built-in d...
// 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
random_line_split
AWS.js
'use strict';
/** * @ngdoc function * @name MSLImageExplorerApp.service:AWS * @description * # AWS * Service of the MSLImageExplorerApp. It initializes AWS SDK with providing credentials * either from Cognito Identity service or environment variables as specified in ENV service. * It initializes a DynamoDB client instance. Th...
/* global AWS, DynamoDB */
random_line_split
AWS.js
'use strict'; /* global AWS, DynamoDB */ /** * @ngdoc function * @name MSLImageExplorerApp.service:AWS * @description * # AWS * Service of the MSLImageExplorerApp. It initializes AWS SDK with providing credentials * either from Cognito Identity service or environment variables as specified in ENV service. * It i...
/** * DynamoDB client object. */ AWS.dynamoDB = new DynamoDB( new AWS.DynamoDB({ region: ENV.dynamoDBRegion, endpoint: ENV.dynamoDBEndpoint })); return AWS; });
{ // Uses environment variables to get AWS credentials. AWS.config.credentials = new AWS.Credentials({ accessKeyId: ENV.accessKeyId, secretAccessKey: ENV.secretAccessKey }); $log.info('AWS credentials initialized with environment variables'); ...
conditional_block
utils_nt.py
# neubot/utils_nt.py # # Copyright (c) 2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU...
elif not os.path.isfile(curpath): raise RuntimeError('%s: Not a file' % curpath) # if uid is None: # uid = os.getuid() # if gid is None: # gid = os.getgid() # os.chown(curpath, uid, gid) os.chmod(curpath, MODE_644)
filep = open(curpath, "w") filep.close()
conditional_block
utils_nt.py
# neubot/utils_nt.py # # Copyright (c) 2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# # I copied the following two functions from utils_posix.py, and I # also commented out the code that couldn't run on Windows NT. # def mkdir_idempotent(curpath, uid=None, gid=None): ''' Idempotent mkdir with 0755 permissions''' if not os.path.exists(curpath): os.mkdir(curpath, MODE_755) elif n...
""" Get password database entry by name """ return PWEntry()
identifier_body
utils_nt.py
# neubot/utils_nt.py # # Copyright (c) 2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# os.close(os.open(curpath, os.O_WRONLY|os.O_CREAT # |os.O_APPEND, MODE_644)) filep = open(curpath, "w") filep.close() elif not os.path.isfile(curpath): raise RuntimeError('%s: Not a file' % curpath) # if uid is None: # uid = os.getuid() # if gid is No...
random_line_split
utils_nt.py
# neubot/utils_nt.py # # Copyright (c) 2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(curpath, uid=None, gid=None): ''' Idempotent touch with 0644 permissions ''' if not os.path.exists(curpath): # os.close(os.open(curpath, os.O_WRONLY|os.O_CREAT # |os.O_APPEND, MODE_644)) filep = open(curpath, "w") filep.close() elif not os.path.isfile(curpath):...
touch_idempotent
identifier_name
linux_net.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # <yamahata at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with...
linux_net.iptables_manager.apply() def plug(self, network, mac_address, gateway=True): LOG.debug("network %s mac_adress %s gateway %s", network, mac_address, gateway) ret = super(LinuxOVSRyuInterfaceDriver, self).plug( network, mac_address, gateway) ...
tables['filter'].add_rule( 'FORWARD', '--in-interface gw-+ --out-interface gw-+ -j DROP')
conditional_block
linux_net.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # <yamahata at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with...
def _get_port_no(dev): out, _err = utils.execute('ovs-vsctl', 'get', 'Interface', dev, 'ofport', run_as_root=True) return int(out.strip()) class LinuxOVSRyuInterfaceDriver(linux_net.LinuxOVSInterfaceDriver): def __init__(self): super(LinuxOVSRyuInterfaceDriver, self)....
random_line_split
linux_net.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # <yamahata at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with...
(self, network, mac_address, gateway=True): LOG.debug("network %s mac_adress %s gateway %s", network, mac_address, gateway) ret = super(LinuxOVSRyuInterfaceDriver, self).plug( network, mac_address, gateway) port_no = _get_port_no(self.get_dev(network)) self...
plug
identifier_name
linux_net.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Isaku Yamahata <yamahata at private email ne jp> # <yamahata at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with...
class LinuxOVSRyuInterfaceDriver(linux_net.LinuxOVSInterfaceDriver): def __init__(self): super(LinuxOVSRyuInterfaceDriver, self).__init__() LOG.debug('ryu rest host %s', FLAGS.linuxnet_ovs_ryu_api_host) self.ryu_client = OFPClient(FLAGS.linuxnet_ovs_ryu_api_host) self.datapath_id...
out, _err = utils.execute('ovs-vsctl', 'get', 'Interface', dev, 'ofport', run_as_root=True) return int(out.strip())
identifier_body
tokenrefresh.py
# -*- coding: utf-8 -*- # Copyright 2015 OpenMarket Ltd
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES...
# # Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
tokenrefresh.py
# -*- coding: utf-8 -*- # Copyright 2015 OpenMarket Ltd # # 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 la...
@defer.inlineCallbacks def on_POST(self, request): body = parse_json_dict_from_request(request) try: old_refresh_token = body["refresh_token"] auth_handler = self.hs.get_handlers().auth_handler (user_id, new_refresh_token) = yield self.store.exchange_refresh...
super(TokenRefreshRestServlet, self).__init__() self.hs = hs self.store = hs.get_datastore()
identifier_body
tokenrefresh.py
# -*- coding: utf-8 -*- # Copyright 2015 OpenMarket Ltd # # 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 la...
(RestServlet): """ Exchanges refresh tokens for a pair of an access token and a new refresh token. """ PATTERN = client_v2_pattern("/tokenrefresh") def __init__(self, hs): super(TokenRefreshRestServlet, self).__init__() self.hs = hs self.store = hs.get_datastore() @...
TokenRefreshRestServlet
identifier_name
traits.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
/// Inject all changes in a single batch. #[cfg(test)] fn inject_batch(&mut self) -> Result<u32, UtilError> { let mut batch = self.backing().transaction(); let res = self.inject(&mut batch)?; self.backing().write(batch).map(|_| res).map_err(Into::into) } }
{ let mut batch = self.backing().transaction(); let mut ops = self.journal_under(&mut batch, now, id)?; if let Some((end_era, canon_id)) = end { ops += self.mark_canonical(&mut batch, end_era, &canon_id)?; } let result = self.backing().write(batch).map(|_| ops).map_err(Into::into); self.flush(); resu...
identifier_body
traits.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
fn consolidate(&mut self, overlay: ::memorydb::MemoryDB); /// Commit all changes in a single batch #[cfg(test)] fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> { let mut batch = self.backing().transaction(); let mut ops = self.journal_under(&mut batch, now, i...
/// Clear internal strucutres. This should called after changes have been written /// to the backing strage fn flush(&self) {} /// Consolidate all the insertions and deletions in the given memory overlay.
random_line_split
traits.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into); self.flush(); result } /// Inject all changes in a single batch. #[cfg(test)] fn inject_batch(&mut self) -> Result<u32, UtilError> { let mut batch = self.backing().transaction(); let res = self.inject(&mut batch)?; self.backin...
{ ops += self.mark_canonical(&mut batch, end_era, &canon_id)?; }
conditional_block
traits.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
(&self) -> usize { 0 } /// Check if this database has any commits fn is_empty(&self) -> bool; /// Get the earliest era in the DB. None if there isn't yet any data in there. fn earliest_era(&self) -> Option<u64> { None } /// Get the latest era in the DB. None if there isn't yet any data in there. fn latest_era(...
journal_size
identifier_name
DrawMenuModule.js
/* * Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyrig...
DrawMenuModule.prototype.addAppsButton = function(btn) { return this.appsButton.menu.add(btn); }; return new DrawMenuModule(); } );
controller: new CopyPasteController() })); };
random_line_split
index.js
am4core.useTheme(am4themes_animated); var chart = am4core.create("chartdiv", am4charts.XYChart); var data = []; var open = 100; var close = 250; for (var i = 1; i < 366; i++)
chart.data = data; var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.grid.template.location = 0; var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); valueAxis.tooltip.disabled = true; var series = chart.series.push(new am4charts.LineSeries()); series.dataFields.dateX = "date"; s...
{ open += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 50); close += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 50); data.push({ date: new Date(2018, 0, i), open: open, close: close }); }
conditional_block
index.js
am4core.useTheme(am4themes_animated); var chart = am4core.create("chartdiv", am4charts.XYChart); var data = []; var open = 100; var close = 250; for (var i = 1; i < 366; i++) { open += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 50); close += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random...
data.push({ date: new Date(2018, 0, i), open: open, close: close }); } chart.data = data; var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.grid.template.location = 0; var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); valueAxis.tooltip.disabled = true; var series = chart.serie...
random_line_split
StreamFileDeleter.ts
"use strict"; import * as fs from 'fs'; import Base from '../Base'; /** * StreamFileDeleter * stream ファイルの削除を行う * @param _streamNumber: stream number */ class StreamFileDeleter extends Base { private streamNumber: number; private intervalId: NodeJS.Timer; constructor(_streamNumber: number) { supe...
dirPath = configJson.streamFilePath; let files = fs.readdirSync(dirPath); let tsFileList: string[] = []; files.forEach((file) => { if(fileNum == 0 && file.match(".m3u8") && file.match(`stream${ this.streamNumber }`)) { tsFileList.push(file); } ...
valId); } private deleteFile(fileNum: number): void { let configJson = this.config.getConfig(); let
identifier_body
StreamFileDeleter.ts
"use strict"; import * as fs from 'fs'; import Base from '../Base'; /** * StreamFileDeleter * stream ファイルの削除を行う * @param _streamNumber: stream number */ class StreamFileDeleter extends Base { private streamNumber: number; private intervalId: NodeJS.Timer; constructor(_streamNumber: number) { supe...
eamFilePath; let files = fs.readdirSync(dirPath); let tsFileList: string[] = []; files.forEach((file) => { if(fileNum == 0 && file.match(".m3u8") && file.match(`stream${ this.streamNumber }`)) { tsFileList.push(file); } if(file.match(".ts") &&...
igJson.str
identifier_name
StreamFileDeleter.ts
"use strict"; import * as fs from 'fs'; import Base from '../Base'; /** * StreamFileDeleter * stream ファイルの削除を行う * @param _streamNumber: stream number */ class StreamFileDeleter extends Base { private streamNumber: number; private intervalId: NodeJS.Timer; constructor(_streamNumber: number) { supe...
gth - fileNum; i++) { if(typeof tsFileList[i] != "undefined" && tsFileList[i] != ".gitkeep") { fs.unlink(`${ dirPath }/${ tsFileList[i] }`, () => {}); this.log.stream.info(`deleted ${tsFileList[i]}`); } }; } } export default StreamFileDeleter;
ist.sort(); for(let i = 0; i < tsFileList.len
conditional_block
StreamFileDeleter.ts
"use strict"; import * as fs from 'fs'; import Base from '../Base'; /** * StreamFileDeleter * stream ファイルの削除を行う
*/ class StreamFileDeleter extends Base { private streamNumber: number; private intervalId: NodeJS.Timer; constructor(_streamNumber: number) { super(); this.streamNumber = _streamNumber; } /** * 全てのファイルを削除する */ public deleteAllFiles(): void { this.log.stream.inf...
* @param _streamNumber: stream number
random_line_split
nga.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import {UserService} from '../pages/users.services'; import { BaThemeConfig } from ...
}
{ return <ModuleWithProviders> { ngModule: NgaModule, providers: [ BaThemeConfigProvider, BaThemeConfig, ...NGA_VALIDATORS, ...NGA_SERVICES ], }; }
identifier_body
nga.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import {UserService} from '../pages/users.services'; import { BaThemeConfig } from ...
...NGA_COMPONENTS ] }) export class NgaModule { static forRoot(): ModuleWithProviders { return <ModuleWithProviders> { ngModule: NgaModule, providers: [ BaThemeConfigProvider, BaThemeConfig, ...NGA_VALIDATORS, ...NGA_SERVICES ], }; } }
...NGA_PIPES, ...NGA_DIRECTIVES,
random_line_split
nga.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import {UserService} from '../pages/users.services'; import { BaThemeConfig } from ...
(): ModuleWithProviders { return <ModuleWithProviders> { ngModule: NgaModule, providers: [ BaThemeConfigProvider, BaThemeConfig, ...NGA_VALIDATORS, ...NGA_SERVICES ], }; } }
forRoot
identifier_name
test_conf.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
try: import unittest2 as unittest except ImportError: import unittest unittest.main()
conditional_block
test_conf.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
if __name__ == "__main__": try: import unittest2 as unittest except ImportError: import unittest unittest.main()
# not in current versions of Splunk. self.assertRaises(client.IllegalOperationException, confs.delete, conf_name) self.assertTrue(conf_name in confs)
random_line_split
test_conf.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
# New stanzas are empty self.assertEqual(len(stanza), 0) # Update works key = testlib.tmpname() val = testlib.tmpname() stanza.update(**{key: val}) self.assertEventuallyTrue(lambda: stanza.refresh() and len(stanza) == 1, pause_time=0.2) self.assertEqual(l...
confs = self.app_service.confs conf_name = testlib.tmpname() self.assertRaises(KeyError, confs.__getitem__, conf_name) self.assertFalse(conf_name in confs) conf = confs.create(conf_name) self.assertTrue(conf_name in confs) self.assertEqual(conf.name, conf_name) ...
identifier_body
test_conf.py
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
(testlib.SDKTestCase): def test_read(self): service = client.connect(**self.opts.kwargs) confs = service.confs # Make sure the collection contains some of the expected entries self.assertTrue('eventtypes' in confs) self.assertTrue('indexes' in confs) self.assertTrue...
TestRead
identifier_name
render.py
from dataclasses import dataclass import io import typing as T import numpy as np @dataclass(frozen=True) class PolygonShape: vertices: T.Tuple[T.Tuple[float]] color: T.Text @dataclass(frozen=True) class Body: x: float y: float angle: float shapes: T.Tuple[PolygonShape] @dataclass(frozen=...
out.write('"/>') def draw_body(body, out): out.write('<g transform="translate({x},{y}) rotate({angle})">'.format( x=body.x, y=body.y, angle=body.angle * 180/np.pi, )) for shape in body.shapes: draw_shape(shape, out) out.write('</g>') def draw_scene(scene, out): xmin, xmax, y...
out.write(' L {} {}'.format(dx, dy))
conditional_block
render.py
from dataclasses import dataclass
@dataclass(frozen=True) class PolygonShape: vertices: T.Tuple[T.Tuple[float]] color: T.Text @dataclass(frozen=True) class Body: x: float y: float angle: float shapes: T.Tuple[PolygonShape] @dataclass(frozen=True) class Scene: bodies: T.Tuple[Body] bounds: T.Tuple[float] # left, rig...
import io import typing as T import numpy as np
random_line_split
render.py
from dataclasses import dataclass import io import typing as T import numpy as np @dataclass(frozen=True) class PolygonShape: vertices: T.Tuple[T.Tuple[float]] color: T.Text @dataclass(frozen=True) class Body: x: float y: float angle: float shapes: T.Tuple[PolygonShape] @dataclass(frozen=...
def draw_body(body, out): out.write('<g transform="translate({x},{y}) rotate({angle})">'.format( x=body.x, y=body.y, angle=body.angle * 180/np.pi, )) for shape in body.shapes: draw_shape(shape, out) out.write('</g>') def draw_scene(scene, out): xmin, xmax, ymin, ymax = scene.bou...
out.write('<path fill="{fill}" d="'.format(fill=shape.color)) dx, dy = shape.vertices[0] out.write('M {} {}'.format(dx, dy)) for (dx, dy) in shape.vertices[1:]: out.write(' L {} {}'.format(dx, dy)) out.write('"/>')
identifier_body
render.py
from dataclasses import dataclass import io import typing as T import numpy as np @dataclass(frozen=True) class PolygonShape: vertices: T.Tuple[T.Tuple[float]] color: T.Text @dataclass(frozen=True) class Body: x: float y: float angle: float shapes: T.Tuple[PolygonShape] @dataclass(frozen=...
: bodies: T.Tuple[Body] bounds: T.Tuple[float] # left, right, top, bottom width: int def draw_shape(shape, out): out.write('<path fill="{fill}" d="'.format(fill=shape.color)) dx, dy = shape.vertices[0] out.write('M {} {}'.format(dx, dy)) for (dx, dy) in shape.vertices[1:]: out.wri...
Scene
identifier_name
setup.py
#!/usr/bin/python import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) setup( name='django-sizefield', version='0.10.ceda', author='Mathieu Leplatre', author_email='contact@mathieu-leplatre.info', url='https://github.com/leplatrem/django-sizefield...
], packages=find_packages(), include_package_data=True, zip_safe=False, classifiers=['Topic :: Utilities', 'Natural Language :: English', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'Environment :: Web ...
license='LPGL, see LICENSE file.', install_requires=[ 'Django',
random_line_split
test_signout.py
import mock from django.test import TestCase from mediaviewer.views.signout import signout class TestSignout(TestCase): def setUp(self): self.logout_patcher = mock.patch('mediaviewer.views.signout.logout') self.mock_logout = self.logout_patcher.start() self.addCleanup(self.logout_patcher...
(self): expected_context = {'active_page': 'logout', 'loggedin': False, 'title': 'Signed out'} expected = self.mock_render.return_value actual = signout(self.request) self.assertEqual(expected, actual) self.mock_logout.ass...
test_signout
identifier_name
test_signout.py
import mock from django.test import TestCase from mediaviewer.views.signout import signout class TestSignout(TestCase): def setUp(self): self.logout_patcher = mock.patch('mediaviewer.views.signout.logout') self.mock_logout = self.logout_patcher.start() self.addCleanup(self.logout_patcher...
expected_context = {'active_page': 'logout', 'loggedin': False, 'title': 'Signed out'} expected = self.mock_render.return_value actual = signout(self.request) self.assertEqual(expected, actual) self.mock_logout.assert_called_once_...
identifier_body
test_signout.py
import mock from django.test import TestCase from mediaviewer.views.signout import signout class TestSignout(TestCase): def setUp(self): self.logout_patcher = mock.patch('mediaviewer.views.signout.logout') self.mock_logout = self.logout_patcher.start() self.addCleanup(self.logout_patcher...
self.request, 'mediaviewer/logout.html', expected_context)
random_line_split
http_parts.rs
//! HTTP parts of a Request/Response interaction use std::collections::HashMap; use std::str::from_utf8; use maplit::hashmap; use crate::bodies::OptionalBody; use crate::content_types::{ContentType, detect_content_type_from_string}; use crate::generators::{Generator, GeneratorCategory, Generators}; use crate::matchi...
() { let request = Request { method: "GET".to_string(), path: "/".to_string(), query: None, headers: Some(hashmap!{ "Content-Type".to_string() => vec!["application/json; charset=UTF-8".to_string()] }), body: OptionalBody::Missing, .. Request::default() }; expect!(request.has_header("Content-Type"))....
http_part_has_header_test
identifier_name
http_parts.rs
//! HTTP parts of a Request/Response interaction use std::collections::HashMap; use std::str::from_utf8; use maplit::hashmap; use crate::bodies::OptionalBody; use crate::content_types::{ContentType, detect_content_type_from_string}; use crate::generators::{Generator, GeneratorCategory, Generators}; use crate::matchi...
else { match self.lookup_content_type() { Some(ref h) => match ContentType::parse(h.as_str()) { Ok(v) => Some(v), Err(_) => self.detect_content_type() }, None => self.detect_content_type() } } } /// Checks if the HTTP Part has the given header fn has_h...
{ body.content_type() }
conditional_block
http_parts.rs
//! HTTP parts of a Request/Response interaction use std::collections::HashMap; use std::str::from_utf8; use maplit::hashmap; use crate::bodies::OptionalBody; use crate::content_types::{ContentType, detect_content_type_from_string}; use crate::generators::{Generator, GeneratorCategory, Generators}; use crate::matchi...
/// Returns a mutable pointer to the body of the HTTP part. fn body_mut(&mut self) -> &mut OptionalBody; /// Returns the matching rules of the HTTP part. fn matching_rules(&self) -> &MatchingRules; /// Returns the matching rules of the HTTP part. fn matching_rules_mut(&mut self) -> &mut MatchingRules; ...
/// Returns the body of the HTTP part. fn body(&self) -> &OptionalBody;
random_line_split
http_parts.rs
//! HTTP parts of a Request/Response interaction use std::collections::HashMap; use std::str::from_utf8; use maplit::hashmap; use crate::bodies::OptionalBody; use crate::content_types::{ContentType, detect_content_type_from_string}; use crate::generators::{Generator, GeneratorCategory, Generators}; use crate::matchi...
/// Checks if the HTTP Part has the given header fn lookup_header_value(&self, header_name: &str) -> Option<String> { match *self.headers() { Some(ref h) => h.iter() .find(|kv| kv.0.to_lowercase() == header_name.to_lowercase()) .map(|kv| kv.1.clone().join(", ")), None => None }...
{ self.lookup_header_value(header_name).is_some() }
identifier_body
igmap.component.spec.ts
// tslint:disable-next-line:max-line-length // modeled after https://github.com/angular/angular/blob/cee2318110eeea115e5f6fc5bfc814cbaa7d90d8/modules/angular2/test/common/directives/ng_for_spec.ts import { TestBed } from '@angular/core/testing'; import { Component, ViewChild } from '@angular/core'; import * as Infragis...
}); }); }); @Component({ selector: 'test-cmp', template: '<div></div>' // "Component 'TestComponent' must have either 'template' or 'templateUrl' set." }) class TestComponent { @ViewChild(Infragistics.IgMapComponent, { static: true }) public viewChild: Infragistics.IgMapComponent; data: a...
random_line_split
igmap.component.spec.ts
// tslint:disable-next-line:max-line-length // modeled after https://github.com/angular/angular/blob/cee2318110eeea115e5f6fc5bfc814cbaa7d90d8/modules/angular2/test/common/directives/ng_for_spec.ts import { TestBed } from '@angular/core/testing'; import { Component, ViewChild } from '@angular/core'; import * as Infragis...
() { this.data = [{ Name: 'Warsaw', Country: 'Poland', Latitude: 52.21, Longitude: 21 }]; } }
constructor
identifier_name
Group.ts
import draw2d from "draw2d"; import PubSub from "pubsub-js"; import cuid from "cuid"; import { menuItem } from "../../common/Menus"; import Colors from "./Colors"; import { Canvas2d, Figure2d } from "./draw2dTypes"; import { FigureDto } from "./StoreDtos"; const def = { id: cuid(), width: 1000, height: (1000 * 1...
extends draw2d.shape.composite.Raft { NAME = "Group"; static groupType = "group"; type = Group.groupType; colorName: string = "none"; nameLabel: Figure2d; descriptionLabel: Figure2d; getName = () => this.nameLabel?.text ?? ""; getDescription = () => this.descriptionLabel?.text ?? ""; constructor(...
Group
identifier_name
Group.ts
import draw2d from "draw2d"; import PubSub from "pubsub-js";
import { menuItem } from "../../common/Menus"; import Colors from "./Colors"; import { Canvas2d, Figure2d } from "./draw2dTypes"; import { FigureDto } from "./StoreDtos"; const def = { id: cuid(), width: 1000, height: (1000 * 150) / 230, description: "Description", }; export default class Group extends draw2d...
import cuid from "cuid";
random_line_split
Group.ts
import draw2d from "draw2d"; import PubSub from "pubsub-js"; import cuid from "cuid"; import { menuItem } from "../../common/Menus"; import Colors from "./Colors"; import { Canvas2d, Figure2d } from "./draw2dTypes"; import { FigureDto } from "./StoreDtos"; const def = { id: cuid(), width: 1000, height: (1000 * 1...
}
{ target.setPosition(4, -24); }
identifier_body
Group.ts
import draw2d from "draw2d"; import PubSub from "pubsub-js"; import cuid from "cuid"; import { menuItem } from "../../common/Menus"; import Colors from "./Colors"; import { Canvas2d, Figure2d } from "./draw2dTypes"; import { FigureDto } from "./StoreDtos"; const def = { id: cuid(), width: 1000, height: (1000 * 1...
} static deserialize(data: FigureDto) { return new Group(data.name, data.description, { id: data.id, width: data.rect.w, height: data.rect.h, }); } serialize(): FigureDto { return { type: this.type, id: this.id, rect: { x: this.x, y: this.y, w: this.width, h: t...
{ selectionPolicy.createResizeHandle = (owner: any, type: any) => { return new draw2d.ResizeHandle({ owner: owner, type: type, width: 15, height: 15, }); }; }
conditional_block
istr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let s: ~str = ~"a big ol' string"; let t: ~str = ~"a big ol' string"; assert!(s == t); let u: ~str = ~"a bad ol' string"; assert!((s != u)); } fn test_heap_log() { let s = ~"a big ol' string"; println!("{}", s); } fn test_stack_add() { assert_eq!(~"a" + "b", ~"ab"); let s: ~str = ~"a"...
test_heap_assign
identifier_name
istr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
test_stack_add(); test_stack_heap_add(); test_heap_add(); test_append(); }
test_heap_assign(); test_heap_log();
random_line_split
istr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn test_heap_log() { let s = ~"a big ol' string"; println!("{}", s); } fn test_stack_add() { assert_eq!(~"a" + "b", ~"ab"); let s: ~str = ~"a"; assert_eq!(s + s, ~"aa"); assert_eq!(~"" + "", ~""); } fn test_stack_heap_add() { assert!((~"a" + "bracadabra" == ~"abracadabra")); } fn test_heap_add() { ...
{ let s: ~str = ~"a big ol' string"; let t: ~str = ~"a big ol' string"; assert!(s == t); let u: ~str = ~"a bad ol' string"; assert!((s != u)); }
identifier_body
distance_sensors.py
import wpilib import math
Long distance sensor: 20cm to 150cm Output is in centimeters Distance can be calculated using 62.28*x ^ -1.092 ''' def __init__(self,num): self.distance = wpilib.AnalogInput(num) def getDistance(self): '''Returns distance in ce...
class SharpIR2Y0A02: ''' Sharp IR sensor GP2Y0A02YK0F
random_line_split
distance_sensors.py
import wpilib import math class SharpIR2Y0A02: ''' Sharp IR sensor GP2Y0A02YK0F Long distance sensor: 20cm to 150cm Output is in centimeters Distance can be calculated using 62.28*x ^ -1.092 ''' def __init__(self,num): self.distance = ...
(self): return self.distance.getVoltage() class SharpIRGP2Y0A41SK0F: ''' Sharp IR sensor GP2Y0A41SK0F Short distance sensor: 4cm to 40cm Output is in centimeters= ''' #short Distance def __init__(self,num): self.distance = wpilib.AnalogInpu...
getVoltage
identifier_name
distance_sensors.py
import wpilib import math class SharpIR2Y0A02: ''' Sharp IR sensor GP2Y0A02YK0F Long distance sensor: 20cm to 150cm Output is in centimeters Distance can be calculated using 62.28*x ^ -1.092 ''' def __init__(self,num): self.distance = ...
def __init__(self, longDist, longOff, shortDist, shortOff): self.longDistance = longDist self.shortDistance = shortDist self.longOff = longOff self.shortOff = shortOff def getDistance(self): long = self.longDistance.getDistance() short = self.shortDi...
identifier_body
geo.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; import { HttpClientModule } from '@angular/common/http'; import { GeoComponent } from './geo.component'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/pla...
component.onInputs(component.coordinates); expect(component.onChanges).toHaveBeenCalledWith(component.coordinates); }); it('click on copy to clipboard', () => { spyOn(component, 'copyToClipBoard'); const element = fixture.debugElement.query(By.css('.geo-copy-to-clipboard')); element.triggerEventHandler('cl...
spyOn(component, 'onChanges');
random_line_split
validations.js
* User.validatesLengthOf('nick', {min: 3, max: 15}); * ``` * Example: length validations with custom error messages * ``` * User.validatesLengthOf('password', {min: 7, message: {min: 'too weak'}}); * User.validatesLengthOf('state', {is: 2, message: {is: 'is not valid state name'}}); * ``` * @param {String} prop...
* Example: length validations * ``` * User.validatesLengthOf('password', {min: 7}); * User.validatesLengthOf('email', {max: 100}); * User.validatesLengthOf('state', {is: 2});
random_line_split
validations.js
(function (isValid) { * isValid; // false * }) *``` * @param {String} propertyName Property name to validate. * @param {Function} validatorFn Custom validation function. * @options {Object} Options See below * @property {String} message Optional error message if property is not valid. Default error...
validationFailed
identifier_name
validations.js
= getConfigurator("inclusion"); /** * Validate exclusion. Require a property value not be in the specified array. * * Example: `Company.validatesExclusionOf('domain', {in: ['www', 'admin']});` * * @param {String} propertyName Property name to validate. * @options {Object} Options * @property {Array} inArray ...
/*! * Custom validator */ function validateCustom(attr, conf, err, options, done) { if (typeof options === "function") { done = options; options = {}; } conf.customValidator.call(this, err, done); } /*! * Uniqueness validator */ function validateUniqueness(attr, conf, err, options, do...
{ if (nullCheck.call(this, attr, conf, err)) return; if (typeof this[attr] === "string") { if (!this[attr].match(conf["with"])) { err(); } } else { err(); } }
identifier_body
associated-types-conditional-dispatch.rs
// run-pass // Test that we evaluate projection predicates to winnow out // candidates during trait selection and method resolution (#20296). // If we don't properly winnow out candidates based on the output type // `Target=[A]`, then the impl marked with `(*)` is seen to conflict // with all the others. // pretty-exp...
(&self) -> &T { self.as_ref().unwrap() } } impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> { type Target = T; fn deref(&self) -> &T { self.helper.helper_borrow() } } pub fn check<T: MyEq>(x: T, y: T) -> bool { let d: DerefWithHelper<Option<T>, T> = DerefWithHelper { helper: ...
helper_borrow
identifier_name
associated-types-conditional-dispatch.rs
// run-pass // Test that we evaluate projection predicates to winnow out // candidates during trait selection and method resolution (#20296). // If we don't properly winnow out candidates based on the output type // `Target=[A]`, then the impl marked with `(*)` is seen to conflict // with all the others. // pretty-exp...
{ }
identifier_body
associated-types-conditional-dispatch.rs
// run-pass // Test that we evaluate projection predicates to winnow out // candidates during trait selection and method resolution (#20296). // If we don't properly winnow out candidates based on the output type // `Target=[A]`, then the impl marked with `(*)` is seen to conflict // with all the others. // pretty-exp...
fn helper_borrow(&self) -> &T { self.as_ref().unwrap() } } impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> { type Target = T; fn deref(&self) -> &T { self.helper.helper_borrow() } } pub fn check<T: MyEq>(x: T, y: T) -> bool { let d: DerefWithHelper<Option<T>, T> = DerefW...
trait Helper<T> { fn helper_borrow(&self) -> &T; } impl<T> Helper<T> for Option<T> {
random_line_split
migrate.py
def migrate_ip(self): """ Migrate to the latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_2_to_3(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2:
self.reload() def migrate_1_to_2(self): """ Migrate from schema 1 to 2. """ if self.schema_version < 1: migrate_0_to_1(self) if self.schema_version == 1: from crits.core.core_migrate import migrate_analysis_results migrate_analysis_results(self) self.schema...
self.schema_version = 3 self.save()
random_line_split
migrate.py
def migrate_ip(self): """ Migrate to the latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_2_to_3(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2: self.schem...
def migrate_0_to_1(self): """ Migrate from schema 0 to 1. """ if self.schema_version < 1: self.schema_version = 1
""" Migrate from schema 1 to 2. """ if self.schema_version < 1: migrate_0_to_1(self) if self.schema_version == 1: from crits.core.core_migrate import migrate_analysis_results migrate_analysis_results(self) self.schema_version = 2 self.save() self.reload(...
identifier_body
migrate.py
def migrate_ip(self): """ Migrate to the latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def
(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2: self.schema_version = 3 self.save() self.reload() def migrate_1_to_2(self): """ Migrate from schema 1 to 2. """ if self.schema...
migrate_2_to_3
identifier_name
migrate.py
def migrate_ip(self): """ Migrate to the latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_2_to_3(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2: self.schem...
self.schema_version = 1
conditional_block
Ping.py
# Copyright (c) 2014 Alcatel-Lucent Enterprise # 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 # # Un...
def __init__(self, ping_response): if not ping_response: raise Exception("Can't create PingData object without ping response data") self.ping_response = ping_response # Extract packets data from statistics section of Ping response result = re.search('(?P<pkt_transmitted>\...
- ping_stdev = standard deviation of ping response time in milliseconds (float) """
random_line_split
Ping.py
# Copyright (c) 2014 Alcatel-Lucent Enterprise # 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 # # Un...
self.ping_response = ping_response # Extract packets data from statistics section of Ping response result = re.search('(?P<pkt_transmitted>\d)\spackets\stransmitted,\s(?P<pkt_received>\d)?\s?\w*\sreceived,\s(?P<pkt_loss>[\d]*?\.?[\d]*)\%\spacket\sloss', self.ping_response) self.pkt_tran...
raise Exception("Can't create PingData object without ping response data")
conditional_block
Ping.py
# Copyright (c) 2014 Alcatel-Lucent Enterprise # 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 # # Un...
self.count = self._config.get('count') self.ping_cmd += " -c " + str(self.count) # Add -W option if requested if self._config.get('timeout'): self.ping_cmd += " -W " + str(self._config.get('timeout')) # Add ping address self.ping_cmd += "...
_mandatory_parameters = [ 'ping_addr' # IP address or hostname of the machine to ping ] _optional_parameters = [ 'requested_data', # (string) Requested data (default is 'status' which returns the status code of ping command execution). See...
identifier_body
Ping.py
# Copyright (c) 2014 Alcatel-Lucent Enterprise # 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 # # Un...
(self, ping_response): if not ping_response: raise Exception("Can't create PingData object without ping response data") self.ping_response = ping_response # Extract packets data from statistics section of Ping response result = re.search('(?P<pkt_transmitted>\d)\spackets\stra...
__init__
identifier_name
opts.rs
{ /// The initial URLs to load. pub urls: Vec<String>, /// How many threads to use for CPU painting (`-t`). /// /// FIXME(pcwalton): This is not currently used. All painting is sequential. pub n_paint_threads: uint, /// True to use GPU painting via Skia-GL, false to use CPU painting via S...
Opts
identifier_name
opts.rs
android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { urls: vec!(), n_paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixe...
{ unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::...
identifier_body
opts.rs
opts)); } pub fn print_debug_usage(app: &str) { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths s...
dump_flow_tree: debug_options.contains(&"dump-flow-tree"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), };
random_line_split
readme_sync.rs
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. // required by `FutureClient` (not used directly in this example) #![feature(plugin)] #![pl...
let (tx, rx) = mpsc::channel(); thread::spawn(move || { let handle = HelloServer.listen("localhost:0", server::Options::default()).unwrap(); tx.send(handle.addr()).unwrap(); handle.run(); }); let client = SyncClient::connect(rx.recv().unwrap(), client::Options::default()).unwrap(...
} fn main() {
random_line_split
readme_sync.rs
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. // required by `FutureClient` (not used directly in this example) #![feature(plugin)] #![pl...
; impl SyncService for HelloServer { fn hello(&self, name: String) -> Result<String, Never> { Ok(format!("Hello from thread {}, {}!", thread::current().name().unwrap(), name)) } } fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let handle = HelloServer.listen("local...
HelloServer
identifier_name
dots_view_spec.js
//= require spec_helper //= require models/dot //= require collections/dots //= require templates/dot_view //= require views/dot_view //= require views/dots_view describe('DotsView', function() { var subject, dot; beforeEach(function() { dots = new Dots(); dots.add([{ id: 1, name: 'Breakfast'...
collection: dots }); SANDBOX.append(subject.render().el); }); describe("when an item is prioritized", function() { it("re-renders with the prioritized item at the top", function() { subject.$('.dot-prioritize[data-dot-id=' + dots.at(2).id + ']').trigger('click'); expect(subject.chil...
priority: 1 }]); subject = new DotsView({
random_line_split
avt.py
######################################################################## # amara/xslt/expressions/avt.py """ Implementation of XSLT attribute value templates """ from amara.xpath import datatypes from amara.xpath.expressions import expression from amara.xslt import XsltError from amara.xslt.expressions import _avt _p...
evaluate = evaluate_as_string def __str__(self): return '{' + self._format % tuple(self._args) + '}'
if not self._args: return self._format result = self._format % tuple(arg.evaluate_as_string(context) for arg in self._args) return datatypes.string(result)
identifier_body
avt.py
######################################################################## # amara/xslt/expressions/avt.py """ Implementation of XSLT attribute value templates """ from amara.xpath import datatypes from amara.xpath.expressions import expression from amara.xslt import XsltError from amara.xslt.expressions import _avt _p...
self._format = u''.join(parts) if not self._args: # use empty format args to force '%%' replacement self._format = datatypes.string(self._format % ()) return def evaluate_as_string(self, context): if not self._args: return self._format re...
if isinstance(part, unicode): if '%' in part: parts[pos] = part.replace('%', '%%') else: parts[pos] = u'%s' args.append(part)
conditional_block
avt.py
######################################################################## # amara/xslt/expressions/avt.py """ Implementation of XSLT attribute value templates """
from amara.xpath import datatypes from amara.xpath.expressions import expression from amara.xslt import XsltError from amara.xslt.expressions import _avt _parse_avt = _avt.parser().parse class avt_expression(expression): __slots__ = ('_format', '_args') def __init__(self, value): try: # pa...
random_line_split
avt.py
######################################################################## # amara/xslt/expressions/avt.py """ Implementation of XSLT attribute value templates """ from amara.xpath import datatypes from amara.xpath.expressions import expression from amara.xslt import XsltError from amara.xslt.expressions import _avt _p...
(self): return '{' + self._format % tuple(self._args) + '}'
__str__
identifier_name
sort.js
'use strict'; function getReferenceMatrix (matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); ...
module.exports.property = function (prop) { const order = [].slice.call(arguments, 1); const dimension = this.getAxis(prop); if (dimension === -1) { throw new Error(`Attempting to do a custom sort on the property ${prop}, which doesn't exist`); } const originalValues = this.axes.find(a => a.property === prop...
{ const referenceMatrix = getReferenceMatrix(matrix, direction); return matrix.clone({ axes: [ Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])}) ], data: referenceMatrix.map(r => r[1]) }); }
identifier_body
sort.js
'use strict'; function getReferenceMatrix (matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); ...
(matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); return matrix.clone({ axes: [ Object...
getReferenceMatrix
identifier_name
sort.js
'use strict'; function getReferenceMatrix (matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); ...
if (dimension === -1) { throw new Error(`Attempting to do a custom sort on the property ${prop}, which doesn't exist`); } const originalValues = this.axes.find(a => a.property === prop).values; // this makes it easier to put the not found items last as the order // will go n = first, n-1 = second, ... , 0 = last...
const dimension = this.getAxis(prop);
random_line_split
models.py
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class
(models.Manager): def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pic...
SessionManager
identifier_name
models.py
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the gi...
return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contai...
s.delete() # Clear sessions with no data.
conditional_block
models.py
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the gi...
verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): encoded_data = base64.decodestring(self.session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper...
random_line_split
models.py
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager):
class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session I...
def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) ...
identifier_body
databases.py
from troveclient import base from troveclient.common import check_for_exceptions from troveclient.common import limit_url from troveclient.common import Paginated import urlparse class Database(base.Resource): """ According to Wikipedia, "A database is a system intended to organize, store, and retrieve ...
databases = body[response_key] databases = [self.resource_class(self, res) for res in databases] return Paginated(databases, next_marker=next_marker, links=links) def list(self, instance, limit=None, marker=None): """ Get a list of all Databases from the instance. ...
parsed_url = urlparse.urlparse(link) query_dict = dict(urlparse.parse_qsl(parsed_url.query)) next_marker = query_dict.get('marker', None)
conditional_block
databases.py
from troveclient import base from troveclient.common import check_for_exceptions from troveclient.common import limit_url from troveclient.common import Paginated import urlparse class Database(base.Resource): """ According to Wikipedia, "A database is a system intended to organize, store, and retrieve ...
def list(self, instance, limit=None, marker=None): """ Get a list of all Databases from the instance. :rtype: list of :class:`Database`. """ return self._list("/instances/%s/databases" % base.getid(instance), "databases", limit, marker) # def ge...
databases = [self.resource_class(self, res) for res in databases] return Paginated(databases, next_marker=next_marker, links=links)
random_line_split
databases.py
from troveclient import base from troveclient.common import check_for_exceptions from troveclient.common import limit_url from troveclient.common import Paginated import urlparse class Database(base.Resource): """ According to Wikipedia, "A database is a system intended to organize, store, and retrieve ...
(self, instance_id, dbname): """Delete an existing database in the specified instance""" url = "/instances/%s/databases/%s" % (instance_id, dbname) resp, body = self.api.client.delete(url) check_for_exceptions(resp, body) def _list(self, url, response_key, limit=None, marker=None): ...
delete
identifier_name
databases.py
from troveclient import base from troveclient.common import check_for_exceptions from troveclient.common import limit_url from troveclient.common import Paginated import urlparse class Database(base.Resource): """ According to Wikipedia, "A database is a system intended to organize, store, and retrieve ...
# def get(self, instance, database): # """ # Get a specific instances. # # :param flavor: The ID of the :class:`Database` to get. # :rtype: :class:`Database` # """ # assert isinstance(instance, Instance) # assert isinstance(database, (Database, int)) # instan...
""" Get a list of all Databases from the instance. :rtype: list of :class:`Database`. """ return self._list("/instances/%s/databases" % base.getid(instance), "databases", limit, marker)
identifier_body
lc826-most-profit-assigning-work.py
# coding=utf-8 import unittest """826. Most Profit Assigning Work https://leetcode.com/problems/most-profit-assigning-work/description/ We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and `profit[i]` is the profit of the `i`th job. Now we have some workers. `worker[i]` is the ability of the `i`th w...
if __name__ == "__main__": unittest.main()
pass
identifier_body
lc826-most-profit-assigning-work.py
# coding=utf-8 import unittest """826. Most Profit Assigning Work https://leetcode.com/problems/most-profit-assigning-work/description/ We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and `profit[i]` is the profit of the `i`th job. Now we have some workers. `worker[i]` is the ability of the `i`th w...
:rtype: int """ def test(self): pass if __name__ == "__main__": unittest.main()
def maxProfitAssignment(self, difficulty, profit, worker): """ :type difficulty: List[int] :type profit: List[int] :type worker: List[int]
random_line_split
lc826-most-profit-assigning-work.py
# coding=utf-8 import unittest """826. Most Profit Assigning Work https://leetcode.com/problems/most-profit-assigning-work/description/ We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and `profit[i]` is the profit of the `i`th job. Now we have some workers. `worker[i]` is the ability of the `i`th w...
unittest.main()
conditional_block
lc826-most-profit-assigning-work.py
# coding=utf-8 import unittest """826. Most Profit Assigning Work https://leetcode.com/problems/most-profit-assigning-work/description/ We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and `profit[i]` is the profit of the `i`th job. Now we have some workers. `worker[i]` is the ability of the `i`th w...
(self): pass if __name__ == "__main__": unittest.main()
test
identifier_name
notifications.page.ts
import { Component, OnDestroy } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { take } from 'rxjs/operators'; import { AppSettings, Notification } from '../app-settings'; import { LoggingService, SpeechService } from '../services'; @Component({ templateUrl: 'notifications.pa...
() { this.settings.setNotifications(this.notifications).catch(error => { this.logger.error('Error setting notifications', error); }); } speak(id: string) { this.getMessage(id).then(message => { this.speech.speak(message); }) } private getMessage(id) { if (this.notifications[id]...
ngOnDestroy
identifier_name