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
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import platform import sys import os from spack import * class Namd(MakefilePackage): """NAMDis a parallel molecular...
(self, spec, prefix): with working_dir(self.build_directory): mkdirp(prefix.bin) install('namd2', prefix.bin) # I'm not sure this is a good idea or if an autoload of the charm # module would not be better. install('charmrun', prefix.bin)
install
identifier_name
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. #
import os from spack import * class Namd(MakefilePackage): """NAMDis a parallel molecular dynamics code designed for high-performance simulation of large biomolecular systems.""" homepage = "http://www.ks.uiuc.edu/Research/namd/" url = "file://{0}/NAMD_2.12_Source.tar.gz".format(os.getcwd()) ...
# SPDX-License-Identifier: (Apache-2.0 OR MIT) import platform import sys
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import platform import sys import os from spack import * class Namd(MakefilePackage): """NAMDis a parallel molecular...
spec = self.spec opts.extend([ '--with-{0}'.format(lib), '--{0}-prefix'.format(lib), spec[lib].prefix ]) @property def arch(self): plat = sys.platform if plat.startswith("linux"): plat = "linux" march = platform.machine() ...
self._copy_arch_file(lib)
conditional_block
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import platform import sys import os from spack import * class Namd(MakefilePackage): """NAMDis a parallel molecular...
fh.write('\n'.join([ 'NAMD_ARCH = {0}'.format(self.arch), 'CHARMARCH = {0}'.format(self.spec['charmpp'].charmarch), 'CXX = {0.cxx} {0.cxx11_flag}'.format( self.compiler), 'CXXOPTS = {0}'.format(optim_...
m64 = '-m64 ' if not spec.satisfies('arch=aarch64:') else '' with working_dir('arch'): with open('{0}.arch'.format(self.build_directory), 'w') as fh: # this options are take from the default provided # configuration files # https://github.com/UIUC-PPL/...
identifier_body
Ftp.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
def process(self, pyfile): parsed_url = urlparse(pyfile.url) netloc = parsed_url.netloc pyfile.name = parsed_url.path.rpartition('/')[2] try: pyfile.name = unquote(str(pyfile.name)).decode('utf8') except: pass if not "@" in netloc: ...
self.chunkLimit = -1 self.resumeDownload = True
identifier_body
Ftp.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
netloc = parsed_url.netloc pyfile.name = parsed_url.path.rpartition('/')[2] try: pyfile.name = unquote(str(pyfile.name)).decode('utf8') except: pass if not "@" in netloc: servers = [x['login'] for x in self.account.getAllAccounts()] if self.a...
def process(self, pyfile): parsed_url = urlparse(pyfile.url)
random_line_split
Ftp.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
(self, pyfile): parsed_url = urlparse(pyfile.url) netloc = parsed_url.netloc pyfile.name = parsed_url.path.rpartition('/')[2] try: pyfile.name = unquote(str(pyfile.name)).decode('utf8') except: pass if not "@" in netloc: servers = [x[...
process
identifier_name
Ftp.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
else: for pwd in pyfile.package().password.splitlines(): if ":" in pwd: self.req.addAuth(pwd.strip()) break self.req.http.c.setopt(pycurl.NOBODY, 1) try: response = self.load(pyfile.url) ...
self.logDebug("Logging on to %s" % netloc) self.req.addAuth(self.account.accounts[netloc]["password"])
conditional_block
BatchFFtoImage.py
""" Batch convert FF files to image files, jpg, png, etc. """ import os import argparse from RMS.Formats.FFfile import read as readFF from RMS.Formats.FFfile import validFFName from RMS.Routines.Image import saveImage def
(dir_path, fmt, add_timestamp=False): # Go through all files in the given folder for file_name in os.listdir(dir_path): # Check if the file is an FF file if validFFName(file_name): # Read the FF file ff = readFF(dir_path, file_name) # Skip the file if it co...
batchFFtoImage
identifier_name
BatchFFtoImage.py
""" Batch convert FF files to image files, jpg, png, etc. """ import os import argparse from RMS.Formats.FFfile import read as readFF from RMS.Formats.FFfile import validFFName from RMS.Routines.Image import saveImage def batchFFtoImage(dir_path, fmt, add_timestamp=False): # Go through all files in the given fo...
if __name__ == "__main__": # COMMAND LINE ARGUMENTS # Init the command line arguments parser arg_parser = argparse.ArgumentParser(description="Convert all FF files in a folder to images.") arg_parser.add_argument('dir_path', nargs=1, metavar='DIR_PATH', type=str, help='Path to directory wi...
if validFFName(file_name): # Read the FF file ff = readFF(dir_path, file_name) # Skip the file if it could not be read if ff is None: continue # Make a filename for the image img_file_name = file_name.replace('fits', '') + fmt ...
conditional_block
BatchFFtoImage.py
""" Batch convert FF files to image files, jpg, png, etc. """ import os import argparse from RMS.Formats.FFfile import read as readFF from RMS.Formats.FFfile import validFFName from RMS.Routines.Image import saveImage def batchFFtoImage(dir_path, fmt, add_timestamp=False): # Go through all files in the given fo...
# COMMAND LINE ARGUMENTS # Init the command line arguments parser arg_parser = argparse.ArgumentParser(description="Convert all FF files in a folder to images.") arg_parser.add_argument('dir_path', nargs=1, metavar='DIR_PATH', type=str, help='Path to directory with FF files.') arg_parser...
if __name__ == "__main__":
random_line_split
BatchFFtoImage.py
""" Batch convert FF files to image files, jpg, png, etc. """ import os import argparse from RMS.Formats.FFfile import read as readFF from RMS.Formats.FFfile import validFFName from RMS.Routines.Image import saveImage def batchFFtoImage(dir_path, fmt, add_timestamp=False): # Go through all files in the given fo...
if __name__ == "__main__": # COMMAND LINE ARGUMENTS # Init the command line arguments parser arg_parser = argparse.ArgumentParser(description="Convert all FF files in a folder to images.") arg_parser.add_argument('dir_path', nargs=1, metavar='DIR_PATH', type=str, help='Path to directory wi...
for file_name in os.listdir(dir_path): # Check if the file is an FF file if validFFName(file_name): # Read the FF file ff = readFF(dir_path, file_name) # Skip the file if it could not be read if ff is None: continue # Make a...
identifier_body
queryReducer.js
export const SET_SORT = 'SET_SORT'; export const SORT_ASC = 'ASC'; export const SORT_DESC = 'DESC'; export const SET_PAGE = 'SET_PAGE'; export const SET_FILTER = 'SET_FILTER'; const oppositeOrder = direction => direction === SORT_DESC ? SORT_ASC : SORT_DESC; /** * This reducer is for the react-router query str...
return { ...previousState, sort: payload, order: SORT_ASC, page: 1, }; case SET_PAGE: return { ...previousState, page: payload }; case SET_FILTER: { return { ...previousState, page: 1, fil...
{ return { ...previousState, order: oppositeOrder(previousState.order), page: 1, }; }
conditional_block
queryReducer.js
export const SET_SORT = 'SET_SORT'; export const SORT_ASC = 'ASC'; export const SORT_DESC = 'DESC'; export const SET_PAGE = 'SET_PAGE'; export const SET_FILTER = 'SET_FILTER'; const oppositeOrder = direction => direction === SORT_DESC ? SORT_ASC : SORT_DESC; /** * This reducer is for the react-router query str...
case SET_FILTER: { return { ...previousState, page: 1, filter: payload }; } default: return previousState; } };
page: 1, }; case SET_PAGE: return { ...previousState, page: payload };
random_line_split
2032002.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the t...
() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (mode == 0 && status == 0) { cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { cm.sendSimple("...#b\r\n#L0#What am I supposed to do h...
start
identifier_name
2032002.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the t...
function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (mode == 0 && status == 0) { cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { cm.sendSimple("...#b\r\n#L0#What am I supposed to do here?#l\r\n#L1#I brought items!#l\r\n#L...
{ status = -1; action(1, 0, 0); }
identifier_body
2032002.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the t...
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Aura * * Adobis's Mission I: Unknown Dead Mine (280010000) * * Zakum PQ NPC (the one and only) */ var status; var selectedType; var scrolls; function star...
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
random_line_split
app.js
/** * Shopware 4 * Copyright © shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission a...
* This file bootstrapps the complete backend structure. */ //{block name="backend/index/application"} Ext.define('Shopware.apps.Index', { /** * Extends from our special controller, which handles the * sub-application behavior and the event bus * @string */ extend:'Enlight.app.SubApplicat...
*
random_line_split
match_view.py
import html import inflect import titlecase from flask import url_for from shared.pd_exception import DoesNotExistException from .. import APP, importing from ..data import match from ..view import View @APP.route('/match/<int:match_id>/') def show_match(match_id: int) -> str: view = Match(match.get_match(matc...
(self) -> str: return self.players_string def og_url(self) -> str: return url_for('show_match', match_id=self.id, _external=True) def og_description(self) -> str: p = inflect.engine() fmt = titlecase.titlecase(p.a(self.format_name)) description = '{fmt} match.'.format(f...
og_title
identifier_name
match_view.py
import html import inflect import titlecase from flask import url_for from shared.pd_exception import DoesNotExistException from .. import APP, importing from ..data import match from ..view import View @APP.route('/match/<int:match_id>/') def show_match(match_id: int) -> str: view = Match(match.get_match(matc...
self.has_game_three = True self.game_three = viewed_match.games[2] if viewed_match.has_unexpected_third_game is None: importing.reimport(viewed_match) self.has_unexpected_third_game = viewed_match.has_unexpected_third_game if viewed_match.is_tournament is None...
super().__init__() if not viewed_match: raise DoesNotExistException() self.match = viewed_match self.id = viewed_match.id self.comment = viewed_match.comment self.format_name = viewed_match.format_name() self.players_string = ' vs '.join([p.name for p in viewe...
identifier_body
match_view.py
import html import inflect import titlecase from flask import url_for from shared.pd_exception import DoesNotExistException from .. import APP, importing from ..data import match from ..view import View @APP.route('/match/<int:match_id>/') def show_match(match_id: int) -> str: view = Match(match.get_match(matc...
if viewed_match.has_unexpected_third_game is None: importing.reimport(viewed_match) self.has_unexpected_third_game = viewed_match.has_unexpected_third_game if viewed_match.is_tournament is None: importing.reimport(viewed_match) self.is_tournament = viewed_match.i...
self.has_game_three = True self.game_three = viewed_match.games[2]
conditional_block
match_view.py
import html import inflect import titlecase from flask import url_for from shared.pd_exception import DoesNotExistException from .. import APP, importing from ..data import match from ..view import View @APP.route('/match/<int:match_id>/') def show_match(match_id: int) -> str: view = Match(match.get_match(matc...
def og_description(self) -> str: p = inflect.engine() fmt = titlecase.titlecase(p.a(self.format_name)) description = '{fmt} match.'.format(fmt=fmt) return description def player_link(name: str) -> str: url = url_for('show_person', person=name) return '<a href="{url}">{name}...
return url_for('show_match', match_id=self.id, _external=True)
random_line_split
PublishingStatusDialogContainer.tsx
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope tha...
import DialogHeader from '../DialogHeader'; import DialogBody from '../DialogBody/DialogBody'; import * as React from 'react'; import PublishingStatusDisplay, { publishingStatusMessages } from '../PublishingStatusDisplay'; import { PublishingStatusDialogContainerProps } from './utils'; const useStyles = makeStyles(() ...
import makeStyles from '@mui/styles/makeStyles'; import { useIntl } from 'react-intl';
random_line_split
PublishingStatusDialogContainer.tsx
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope tha...
(props: PublishingStatusDialogContainerProps) { const { status, enabled, published, lockOwner, lockTTL, numberOfItems, totalItems, publishingTarget, submissionId, onClose, onRefresh, onUnlock, onStartStop, isFetching } = props; const classes = useStyles(); ...
PublishingStatusDialogContainer
identifier_name
PublishingStatusDialogContainer.tsx
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope tha...
<> <DialogHeader title={formatMessage(publishingStatusMessages.publishingStatus)} onCloseButtonClick={onClose} rightActions={[ onUnlock && { icon: { id: '@mui/icons-material/LockOpenRounded' }, onClick: onUnlock, tooltip: formatMessage(publ...
{ const { status, enabled, published, lockOwner, lockTTL, numberOfItems, totalItems, publishingTarget, submissionId, onClose, onRefresh, onUnlock, onStartStop, isFetching } = props; const classes = useStyles(); const { formatMessage } = useIntl(); return...
identifier_body
distinct.rs
extern crate timely; use std::fmt::Debug; use std::hash::Hash; use timely::communication::Data; use timely::progress::timestamp::RootTimestamp; use timely::progress::nested::Summary::Local; use timely::construction::*; use timely::construction::operators::*; fn main() { timely::execute(std::env::args(), |root| ...
input2.advance_to(1000000); input1.close(); input2.close(); // spin while root.step() { } }); } fn create_subgraph<G: GraphBuilder, D>(builder: &G, source1: &Stream<G, D>, source2: &Stream<G, D>) -> (Stream<G, D>, Stream<G, D>) where D: Data+Hash+Eq+Debug, G::Timestamp: Has...
root.step(); input1.advance_to(1000000);
random_line_split
distinct.rs
extern crate timely; use std::fmt::Debug; use std::hash::Hash; use timely::communication::Data; use timely::progress::timestamp::RootTimestamp; use timely::progress::nested::Summary::Local; use timely::construction::*; use timely::construction::operators::*; fn main() { timely::execute(std::env::args(), |root| ...
<G: GraphBuilder, D>(builder: &G, source1: &Stream<G, D>, source2: &Stream<G, D>) -> (Stream<G, D>, Stream<G, D>) where D: Data+Hash+Eq+Debug, G::Timestamp: Hash { builder.clone().subcomputation::<u64,_,_>(|subgraph| { (subgraph.enter(source1).leave(), subgraph.enter(source2).leave()) }) }
create_subgraph
identifier_name
distinct.rs
extern crate timely; use std::fmt::Debug; use std::hash::Hash; use timely::communication::Data; use timely::progress::timestamp::RootTimestamp; use timely::progress::nested::Summary::Local; use timely::construction::*; use timely::construction::operators::*; fn main() { timely::execute(std::env::args(), |root| ...
{ builder.clone().subcomputation::<u64,_,_>(|subgraph| { (subgraph.enter(source1).leave(), subgraph.enter(source2).leave()) }) }
identifier_body
lib.rs
// This is a part of rust-encoding. // // Any copyright is dedicated to the Public Domain. // https://creativecommons.org/publicdomain/zero/1.0/ //! Single-byte index tables for //! [rust-encoding](https://github.com/lifthrasiir/rust-encoding). #![cfg_attr(test, feature(test))] #[cfg(test)] #[macro_use] extern crate...
pub mod koi8_r; /// KOI8-U. pub mod koi8_u; /// MacRoman. pub mod macintosh; /// Windows code page 874. pub mod windows_874; /// Windows code page 1250. pub mod windows_1250; /// Windows code page 1251. pub mod windows_1251; /// Windows code page 1252. pub mod windows_1252; /// Windows code page 1253. pub mod wi...
/// KOI8-R.
random_line_split
future.ts
Delegate implements Kernel.IFuture { /** * Construct a new KernelFutureHandler. */ constructor(cb: () => void, msg: KernelMessage.IShellMessage, expectShell: boolean, disposeOnDone: boolean) { super(cb); this._msg = msg; if (!expectShell) { this._setFlag(Private.KernelFutureFlag.GotReply); ...
(flag: Private.KernelFutureFlag): boolean { return (this._status & flag) !== 0; } /** * Set the given future flag. */ private _setFlag(flag: Private.KernelFutureFlag): void { this._status |= flag; } private _msg: KernelMessage.IShellMessage = null; private _status = 0; private _stdin: (msg...
_testFlag
identifier_name
future.ts
Delegate implements Kernel.IFuture { /** * Construct a new KernelFutureHandler. */ constructor(cb: () => void, msg: KernelMessage.IShellMessage, expectShell: boolean, disposeOnDone: boolean) { super(cb); this._msg = msg; if (!expectShell) { this._setFlag(Private.KernelFutureFlag.GotReply); ...
/** * Test whether the HookList has been disposed. */ get isDisposed(): boolean { return (this._hooks === null); } /** * Dispose the hook list. */ dispose(): void { this._hooks = null; } /** * Schedule a cleanup of the list, removing any hooks that hav...
random_line_split
future.ts
implements Kernel.IFuture { /** * Construct a new KernelFutureHandler. */ constructor(cb: () => void, msg: KernelMessage.IShellMessage, expectShell: boolean, disposeOnDone: boolean) { super(cb); this._msg = msg; if (!expectShell) { this._setFlag(Private.KernelFutureFlag.GotReply); } ...
private _handleIOPub(msg: KernelMessage.IIOPubMessage): void { let process = this._hooks.process(msg); let iopub = this._iopub; if (process && iopub) { iopub(msg); } if (KernelMessage.isStatusMsg(msg) && msg.content.execution_state === 'idle') { this._setFlag(Private.KernelFutureFlag.G...
{ let stdin = this._stdin; if (stdin) { stdin(msg); } }
identifier_body
future.ts
implements Kernel.IFuture { /** * Construct a new KernelFutureHandler. */ constructor(cb: () => void, msg: KernelMessage.IShellMessage, expectShell: boolean, disposeOnDone: boolean) { super(cb); this._msg = msg; if (!expectShell) { this._setFlag(Private.KernelFutureFlag.GotReply); } ...
this._setFlag(Private.KernelFutureFlag.GotReply); if (this._testFlag(Private.KernelFutureFlag.GotIdle)) { this._handleDone(); } } private _handleStdin(msg: KernelMessage.IStdinMessage): void { let stdin = this._stdin; if (stdin) { stdin(msg); } } private _handleIOPub(msg: KernelMess...
{ reply(msg); }
conditional_block
utils.js
import { endGlobalLoad } from '../store'; /** * Tells us if input looks like promise or not * @param {Mixed} obj * @return {Boolean} */ export function isPromise(obj) { return typeof obj === 'object' && obj && obj.then instanceof Function; } /** * Utility to be able to iterate over array of promises in an asy...
/** * Helper to load data on server * @param {Mixed} args * @return {Promise} */ export function loadOnServer(args) { return loadAsyncConnect(args).then(() => { args.store.dispatch(endGlobalLoad()); }); }
{ return loadAsyncConnect({ ...props, filter: (a, b) => !props.filter(a, b) }); }
identifier_body
utils.js
import { endGlobalLoad } from '../store';
* @param {Mixed} obj * @return {Boolean} */ export function isPromise(obj) { return typeof obj === 'object' && obj && obj.then instanceof Function; } /** * Utility to be able to iterate over array of promises in an async fashion * @param {Array} iterable * @param {Function} iterator * @return {Promise} */...
/** * Tells us if input looks like promise or not
random_line_split
utils.js
import { endGlobalLoad } from '../store'; /** * Tells us if input looks like promise or not * @param {Mixed} obj * @return {Boolean} */ export function isPromise(obj) { return typeof obj === 'object' && obj && obj.then instanceof Function; } /** * Utility to be able to iterate over array of promises in an asy...
(components, iterator) { const l = components.length; for (let i = 0; i < l; i++) { const component = components[i]; if (typeof component === 'object') { const keys = Object.keys(component); keys.forEach(key => iterator(component[key], i, key)); } else { iterator(component, i); } ...
eachComponents
identifier_name
utils.js
import { endGlobalLoad } from '../store'; /** * Tells us if input looks like promise or not * @param {Mixed} obj * @return {Boolean} */ export function isPromise(obj) { return typeof obj === 'object' && obj && obj.then instanceof Function; } /** * Utility to be able to iterate over array of promises in an asy...
else { iterator(component, i); } } } /** * Returns flattened array of components that are wrapped with reduxAsyncConnect * @param {Array} components * @return {Array} */ export function filterAndFlattenComponents(components) { const flattened = []; eachComponents(components, component => { if...
{ const keys = Object.keys(component); keys.forEach(key => iterator(component[key], i, key)); }
conditional_block
lib.rs
pub fn bottle_or_bottles(n: i32) -> &'static str { match n { 1 => "bottle", _ => "bottles", } } pub fn sing(n: i32) { for i in (1..n + 1).rev() { println!( "{0} {1} of beer on the wall, {0} {1} of beer.", i, bottle_or_bottles(i) ); ...
n ); }
random_line_split
lib.rs
pub fn bottle_or_bottles(n: i32) -> &'static str { match n { 1 => "bottle", _ => "bottles", } } pub fn
(n: i32) { for i in (1..n + 1).rev() { println!( "{0} {1} of beer on the wall, {0} {1} of beer.", i, bottle_or_bottles(i) ); println!( "Take one down and pass it around, {0} {1} of beer on the wall!", i - 1, bottle_or_bo...
sing
identifier_name
lib.rs
pub fn bottle_or_bottles(n: i32) -> &'static str { match n { 1 => "bottle", _ => "bottles", } } pub fn sing(n: i32)
{ for i in (1..n + 1).rev() { println!( "{0} {1} of beer on the wall, {0} {1} of beer.", i, bottle_or_bottles(i) ); println!( "Take one down and pass it around, {0} {1} of beer on the wall!", i - 1, bottle_or_bottles(i -...
identifier_body
test_interaction.py
import numpy as np import numpy.testing as npt import pandas as pd import pytest from .. import interaction as inter @pytest.fixture def choosers():
@pytest.fixture def alternatives(): return pd.DataFrame( {'var2': range(10, 20), 'var3': range(20, 30)}, index=pd.Index([x for x in 'abcdefghij'], name='thing_id')) def test_interaction_dataset_sim(choosers, alternatives): sample, merged, chosen = inter.mnl_interaction_dataset( ...
return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']})
identifier_body
test_interaction.py
import numpy as np import numpy.testing as npt import pandas as pd import pytest from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( ...
(choosers, alternatives): sample, merged, chosen = inter.mnl_interaction_dataset( choosers, alternatives, len(alternatives)) # chosen should be len(choosers) rows * len(alternatives) cols assert chosen.shape == (len(choosers), len(alternatives)) assert chosen[:, 0].sum() == len(choosers) as...
test_interaction_dataset_sim
identifier_name
test_interaction.py
import numpy as np import numpy.testing as npt import pandas as pd import pytest
from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( {'var2': range(10, 20), 'var3': range(20, 30)}, index=pd....
random_line_split
publish-gh-release-notes.py
""" Script used to publish GitHub release notes extracted from CHANGELOG.rst. This script is meant to be executed after a successful deployment in GitHub actions. Uses the following environment variables: * GIT_TAG: the name of the tag of the current commit. * GH_RELEASE_NOTES_TOKEN: a personal access token with 're...
token = os.environ.get("GH_RELEASE_NOTES_TOKEN") if not token: print("GH_RELEASE_NOTES_TOKEN not set", file=sys.stderr) return 1 slug = os.environ.get("GITHUB_REPOSITORY") if not slug: print("GITHUB_REPOSITORY not set", file=sys.stderr) return 1 rst_body = parse_c...
tag_name = os.environ.get("GITHUB_REF") if not tag_name: print("tag_name not given and $GITHUB_REF not set", file=sys.stderr) return 1 if tag_name.startswith("refs/tags/"): tag_name = tag_name[len("refs/tags/") :]
conditional_block
publish-gh-release-notes.py
""" Script used to publish GitHub release notes extracted from CHANGELOG.rst. This script is meant to be executed after a successful deployment in GitHub actions. Uses the following environment variables: * GIT_TAG: the name of the tag of the current commit. * GH_RELEASE_NOTES_TOKEN: a personal access token with 're...
print(md_body, file=sys.stderr) return 5 print() print(f"Release notes for {tag_name} published successfully:") print(f"https://github.com/{slug}/releases/tag/{tag_name}") print() return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
md_body = convert_rst_to_md(rst_body) if not publish_github_release(slug, token, tag_name, md_body): print("Could not publish release notes:", file=sys.stderr)
random_line_split
publish-gh-release-notes.py
""" Script used to publish GitHub release notes extracted from CHANGELOG.rst. This script is meant to be executed after a successful deployment in GitHub actions. Uses the following environment variables: * GIT_TAG: the name of the tag of the current commit. * GH_RELEASE_NOTES_TOKEN: a personal access token with 're...
def convert_rst_to_md(text): return pypandoc.convert_text( text, "md", format="rst", extra_args=["--wrap=preserve"] ) def main(argv): if len(argv) > 1: tag_name = argv[1] else: tag_name = os.environ.get("GITHUB_REF") if not tag_name: print("tag_name not g...
p = Path(__file__).parent.parent / "doc/en/changelog.rst" changelog_lines = p.read_text(encoding="UTF-8").splitlines() title_regex = re.compile(r"pytest (\d\.\d+\.\d+) \(\d{4}-\d{2}-\d{2}\)") consuming_version = False version_lines = [] for line in changelog_lines: m = title_regex.match(lin...
identifier_body
publish-gh-release-notes.py
""" Script used to publish GitHub release notes extracted from CHANGELOG.rst. This script is meant to be executed after a successful deployment in GitHub actions. Uses the following environment variables: * GIT_TAG: the name of the tag of the current commit. * GH_RELEASE_NOTES_TOKEN: a personal access token with 're...
(slug, token, tag_name, body): github = github3.login(token=token) owner, repo = slug.split("/") repo = github.repository(owner, repo) return repo.create_release(tag_name=tag_name, body=body) def parse_changelog(tag_name): p = Path(__file__).parent.parent / "doc/en/changelog.rst" changelog_lin...
publish_github_release
identifier_name
hooks.ts
/// <reference path="../../../../typings/meteor-cucumber/meteor-cucumber.d.ts"/> /// <reference path="../../../../typings/bluebird/bluebird.d.ts"/> import mc = require('meteor-cucumber'); import Promise = require('bluebird'); var parseCSS = require('webdriverio/lib/helpers/parseCSS.js'); 'use strict'; function define...
self.browser.addCommand('getElementIdText', function(id:string, selector:string) { var self = <mc.WebdriverIO<any>>this; return self.getElementId(id, selector).then( (id2:string) => { return self.elementIdText(id2).then( (result:any) => { return result.value;...
else return result.value.ELEMENT; } }, true);
random_line_split
hooks.ts
/// <reference path="../../../../typings/meteor-cucumber/meteor-cucumber.d.ts"/> /// <reference path="../../../../typings/bluebird/bluebird.d.ts"/> import mc = require('meteor-cucumber'); import Promise = require('bluebird'); var parseCSS = require('webdriverio/lib/helpers/parseCSS.js'); 'use strict'; function define...
}, true); self.browser.addCommand('getElementIdText', function(id:string, selector:string) { var self = <mc.WebdriverIO<any>>this; return self.getElementId(id, selector).then( (id2:string) => { return self.elementIdText(id2).then( (result:any) => { retur...
{ if (!result) throw new Error("No element matching id=${id} and selector=${selector}"); else return result.value.ELEMENT; }
identifier_body
hooks.ts
/// <reference path="../../../../typings/meteor-cucumber/meteor-cucumber.d.ts"/> /// <reference path="../../../../typings/bluebird/bluebird.d.ts"/> import mc = require('meteor-cucumber'); import Promise = require('bluebird'); var parseCSS = require('webdriverio/lib/helpers/parseCSS.js'); 'use strict'; function define...
(result:any): string[] { var ids:string[] = []; for (var i = 0; i < result.value.length; i++) { ids.push(result.value[i].ELEMENT); } return ids; } }, true); self.browser.addCommand('getElementId', function(id:string, selector:string) { var self = <mc.Webdri...
handleResult
identifier_name
hooks.ts
/// <reference path="../../../../typings/meteor-cucumber/meteor-cucumber.d.ts"/> /// <reference path="../../../../typings/bluebird/bluebird.d.ts"/> import mc = require('meteor-cucumber'); import Promise = require('bluebird'); var parseCSS = require('webdriverio/lib/helpers/parseCSS.js'); 'use strict'; function define...
else { return self.elementIdElements(id, selector).then(handleResult); } function handleResult(result:any): string[] { var ids:string[] = []; for (var i = 0; i < result.value.length; i++) { ids.push(result.value[i].ELEMENT); } return ids; } }, tru...
{ selector = id; return self.elements(selector).then(handleResult); }
conditional_block
TabBar.tsx
import { themeGet } from "@styled-system/theme-get" import React from "react" import { Animated, View } from "react-native" import styled from "styled-components/native" import { Box, ClassTheme, Sans } from "palette" /** * Nearly all props are given by the ScrollableTabView, * these are prefixed with Auto: */ int...
flex: 1; ` const Underline = Animated.View const Tabs = styled.View` height: 50px; flex-direction: row; justify-content: space-around; ` const TabButton = styled.View<{ spaceEvenly?: boolean; active?: boolean }>` align-items: center; justify-content: center; padding-top: 5; flex-grow: 1; ${(p) => p...
} const Button = styled.TouchableWithoutFeedback`
random_line_split
puback.rs
//! PUBACK use std::io::Read; use crate::control::variable_header::PacketIdentifier; use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{DecodablePacket, PacketError}; use crate::Decodable; /// `PUBACK` packet #[derive(Debug, Eq, PartialEq, Clone)] pub struct PubackPacket { fixed_head...
} } pub fn packet_identifier(&self) -> u16 { self.packet_identifier.0 } pub fn set_packet_identifier(&mut self, pkid: u16) { self.packet_identifier.0 = pkid; } } impl DecodablePacket for PubackPacket { type DecodePacketError = std::convert::Infallible; fn decode_p...
random_line_split
puback.rs
//! PUBACK use std::io::Read; use crate::control::variable_header::PacketIdentifier; use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{DecodablePacket, PacketError}; use crate::Decodable; /// `PUBACK` packet #[derive(Debug, Eq, PartialEq, Clone)] pub struct PubackPacket { fixed_head...
pub fn packet_identifier(&self) -> u16 { self.packet_identifier.0 } pub fn set_packet_identifier(&mut self, pkid: u16) { self.packet_identifier.0 = pkid; } } impl DecodablePacket for PubackPacket { type DecodePacketError = std::convert::Infallible; fn decode_packet<R: Read>(...
{ PubackPacket { fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishAcknowledgement), 2), packet_identifier: PacketIdentifier(pkid), } }
identifier_body
puback.rs
//! PUBACK use std::io::Read; use crate::control::variable_header::PacketIdentifier; use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{DecodablePacket, PacketError}; use crate::Decodable; /// `PUBACK` packet #[derive(Debug, Eq, PartialEq, Clone)] pub struct PubackPacket { fixed_head...
(pkid: u16) -> PubackPacket { PubackPacket { fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishAcknowledgement), 2), packet_identifier: PacketIdentifier(pkid), } } pub fn packet_identifier(&self) -> u16 { self.packet_identifier.0 } ...
new
identifier_name
TestMapToWindowLevelColors.py
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() RANGE = 150 MAX_ITERATIONS_1 = RANGE MAX_ITERATIONS_2 = RANGE XRAD = 200 YRAD = 200 mandelbrot1 = vtk.vtkImageMandelbrotSource() mandelbrot1.SetMaximumNumberOfIterations...
viewer.SetInputConnection(mapToWL.GetOutputPort()) viewer.SetColorWindow(255.0) viewer.SetColorLevel(127.5) viewer.Render()
viewer = vtk.vtkImageViewer()
random_line_split
vmsite.js
/** * list country.js: General Javascript Library for VirtueMart Administration * Note Patrick kohl : Found many bugs, completly brake in case of multiple list! * Now the json cache (optCache) is common for all calls(states are always same for each country) * and not set for each select list anymore. * @package Vi...
} }); } }; $.fn.vm2front = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + met...
{ var label = opt.find("option[value='"+dataValue+"']").text(); var group ='<optgroup id="'+id+'group'+dataValue+'" label="'+label+'">'; $.each( datas , function( key, value) { //if (value) group +='<option value="'+ key +'">'+ value.v +'</option>'; if (value) group +='<option value="'+ valu...
conditional_block
vmsite.js
/** * list country.js: General Javascript Library for VirtueMart Administration * Note Patrick kohl : Found many bugs, completly brake in case of multiple list! * Now the json cache (optCache) is common for all calls(states are always same for each country) * and not set for each select list anymore. * @package Vi...
list: function(options) { var self = this ; var dest = options.dest; var ids = options.ids; if (ids.length) methods.update(self,dest,ids); $(self).change( function() { methods.update(self,dest)}); }, update: function(org,dest,ids) { var opt = $(org), optValues = opt.val() || [], byAjax ...
(function($){ var undefined, optCache = [], ids, methods = {
random_line_split
dedicatedworkerglobalscope.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::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::Ded...
(worker_url: Url, worker: TrustedWorkerAddress, cx: Rc<Cx>, resource_task: ResourceTask, parent_sender: ScriptChan, own_sender: ScriptChan, receiver: Receiver<ScriptMsg>)...
new_inherited
identifier_name
dedicatedworkerglobalscope.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::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::Ded...
unsafe { JS_ClearPendingException(cx); } return Err(DataClone); } let ScriptChan(ref sender) = self.parent_sender; sender.send(WorkerPostMessage(self.worker, data, nbytes)); Ok(()) } event_handler!(message, GetOnmessage, SetOnmessage) } trait PrivateDed...
ptr::null(), ptr::null_mut()) }; if result == 0 {
random_line_split
spherical-portal-link.js
import Constants from '../constants'; import LinkDrawable from './link'; import SphericalPortalLinkMesh from '../mesh/spherical-portal-link'; /** * Represents a portal link that follows the surface of a sphere. * * Hooray for custom shaders, etc! */ class SphericalPortalLinkDrawable extends LinkDrawable { /** ...
(manager) { this.mesh = new SphericalPortalLinkMesh( manager._gl, this.radius, this.start, this.end, this.color, this.startPercent, this.endPercent ); return super.init(manager); } updateView(viewProject, view, project) { super.updateView(viewProject, view,...
init
identifier_name
spherical-portal-link.js
import Constants from '../constants'; import LinkDrawable from './link'; import SphericalPortalLinkMesh from '../mesh/spherical-portal-link'; /** * Represents a portal link that follows the surface of a sphere. * * Hooray for custom shaders, etc! */ class SphericalPortalLinkDrawable extends LinkDrawable { /** ...
this.endPercent = endPercent; } /** * Constructs a mesh for the link, then initializes the remaining assets. * @param {AssetManager} manager AssetManager containing the program/texture * @return {Boolean} Success/failure */ init(manager) { this.mesh = new SphericalPortalLinkMesh...
random_line_split
spherical-portal-link.js
import Constants from '../constants'; import LinkDrawable from './link'; import SphericalPortalLinkMesh from '../mesh/spherical-portal-link'; /** * Represents a portal link that follows the surface of a sphere. * * Hooray for custom shaders, etc! */ class SphericalPortalLinkDrawable extends LinkDrawable { /** ...
updateView(viewProject, view, project) { super.updateView(viewProject, view, project); this.uniforms.u_model = this.model; } } export default SphericalPortalLinkDrawable;
{ this.mesh = new SphericalPortalLinkMesh( manager._gl, this.radius, this.start, this.end, this.color, this.startPercent, this.endPercent ); return super.init(manager); }
identifier_body
2DVisResult.ts
import {Rectangle} from "./Rectangle"; import {RectangleBin} from "./RectangleBin"; import {node,pTree} from "./CodedSchemes/nLeafBinaryTree/pTree"; import {NLBT} from "./CodedSchemes/nLeafBinaryTree/NLBT"; import {TwoDPackingAlg} from './TwoDPackingAlg'; export class TwoDVisualizationBackend { packedBinCTX:Canvas...
} this.alg = new NLBT(new RectangleBin(10,10),this.itemsToPack,this.recurDepth,this.packedBinCTX); } drawItemsToBePlaced(){ this.stagingAreaCTX.clearRect(0,0,this.stagingAreaCTX.canvas.clientWidth,this.stagingAreaCTX.canvas.clientHeight); let xOffset = 0; let itemSpacin...
{ let packableItem = new Rectangle(0.1*Math.ceil(Math.random()/0.1),0.1*Math.ceil(Math.random()/0.1)) this.itemsToPack.push(packableItem); }
conditional_block
2DVisResult.ts
import {Rectangle} from "./Rectangle"; import {RectangleBin} from "./RectangleBin"; import {node,pTree} from "./CodedSchemes/nLeafBinaryTree/pTree"; import {NLBT} from "./CodedSchemes/nLeafBinaryTree/NLBT"; import {TwoDPackingAlg} from './TwoDPackingAlg'; export class TwoDVisualizationBackend { packedBinCTX:Canvas...
(){ this.stagingAreaCTX.clearRect(0,0,this.stagingAreaCTX.canvas.clientWidth,this.stagingAreaCTX.canvas.clientHeight); let xOffset = 0; let itemSpacing = .1; this.itemsToPack.forEach((rect)=>{ rect.xPos = xOffset; xOffset += rect.width; xOffset += item...
drawItemsToBePlaced
identifier_name
2DVisResult.ts
import {Rectangle} from "./Rectangle"; import {RectangleBin} from "./RectangleBin"; import {node,pTree} from "./CodedSchemes/nLeafBinaryTree/pTree"; import {NLBT} from "./CodedSchemes/nLeafBinaryTree/NLBT"; import {TwoDPackingAlg} from './TwoDPackingAlg'; export class TwoDVisualizationBackend { packedBinCTX:Canvas...
packAllItems(){ this.alg.placeAllRects(); } drawLookAheadSolution(){ this.lookAheadCTX.clearRect(0,0,this.lookAheadCTX.canvas.clientWidth,this.lookAheadCTX.canvas.clientHeight); this.alg.lookAheadSolution.draw(this.lookAheadCTX); } drawPackedBin(){ this.packedBinCT...
{ this.stagingAreaCTX.clearRect(0,0,this.stagingAreaCTX.canvas.clientWidth,this.stagingAreaCTX.canvas.clientHeight); let xOffset = 0; let itemSpacing = .1; this.itemsToPack.forEach((rect)=>{ rect.xPos = xOffset; xOffset += rect.width; xOffset += itemSp...
identifier_body
2DVisResult.ts
import {Rectangle} from "./Rectangle"; import {RectangleBin} from "./RectangleBin"; import {node,pTree} from "./CodedSchemes/nLeafBinaryTree/pTree"; import {NLBT} from "./CodedSchemes/nLeafBinaryTree/NLBT"; import {TwoDPackingAlg} from './TwoDPackingAlg'; export class TwoDVisualizationBackend { packedBinCTX:Canvas...
}); } packAllItems(){ this.alg.placeAllRects(); } drawLookAheadSolution(){ this.lookAheadCTX.clearRect(0,0,this.lookAheadCTX.canvas.clientWidth,this.lookAheadCTX.canvas.clientHeight); this.alg.lookAheadSolution.draw(this.lookAheadCTX); } drawPackedBin(){ ...
rect.draw(this.stagingAreaCTX);
random_line_split
edge_3d_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test case for Edge3D. """ import unittest from catplot.grid_components.nodes import Node2D, Node3D from catplot.grid_components.edges import Edge2D, Edge3D class Edge3DTest(unittest.TestCase): def setUp(self): self.maxDiff = True def test_construc...
self.assertListEqual(edge.x.tolist(), ref_x) self.assertListEqual(edge.y.tolist(), ref_x) self.assertListEqual(edge.z.tolist(), ref_x) if "__main__" == __name__: suite = unittest.TestLoader().loadTestsFromTestCase(Edge3DTest) unittest.TextTestRunner(verbosity=2).run(suite)
""" Test the edge can be moved correctly. """ node1 = Node3D([1.0, 1.0, 1.0], color="#595959", width=1) node2 = Node3D([0.5, 0.5, 0.5], color="#595959", width=1) edge = Edge3D(node1, node2, n=10) edge.move([0.5, 0.5, 0.5]) ref_x = [1.5, 1.45454545454545...
identifier_body
edge_3d_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test case for Edge3D. """ import unittest from catplot.grid_components.nodes import Node2D, Node3D from catplot.grid_components.edges import Edge2D, Edge3D class Edge3DTest(unittest.TestCase): def setUp(self): self.maxDiff = True def test_construc...
self.assertListEqual(edge.y.tolist(), ref_x) self.assertListEqual(edge.z.tolist(), ref_x) if "__main__" == __name__: suite = unittest.TestLoader().loadTestsFromTestCase(Edge3DTest) unittest.TextTestRunner(verbosity=2).run(suite)
1.0909090909090908, 1.0454545454545454, 1.0] self.assertListEqual(edge.x.tolist(), ref_x)
random_line_split
edge_3d_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test case for Edge3D. """ import unittest from catplot.grid_components.nodes import Node2D, Node3D from catplot.grid_components.edges import Edge2D, Edge3D class Edge3DTest(unittest.TestCase): def setUp(self): self.maxDiff = True def test_construc...
suite = unittest.TestLoader().loadTestsFromTestCase(Edge3DTest) unittest.TextTestRunner(verbosity=2).run(suite)
conditional_block
edge_3d_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test case for Edge3D. """ import unittest from catplot.grid_components.nodes import Node2D, Node3D from catplot.grid_components.edges import Edge2D, Edge3D class Edge3DTest(unittest.TestCase): def setUp(self): self.maxDiff = True def
(self): """ Test we can construct Grid2DNode correctly. """ node1 = Node3D([1.0, 1.0, 1.0], color="#595959", width=1) node2 = Node3D([0.5, 0.5, 0.5], color="#595959", width=1) edge = Edge3D(node1, node2, n=10) ref_x = [1.0, 0.9545454545454546, ...
test_construction_and_query
identifier_name
cookies.js
SIN.setCookie = function (key, value, options) { options = options || {}; value = value || ''; if (typeof options.expires === 'number') { var ms = options.expires * 1000 * 60 * 60 * 24; options.expires = new Date(Date.now() + ms); } document.cookie = [ encodeURIComponent(ke...
return result; }; SIN.deleteCookie = function (key, options) { options = options || {}; options.expires = -1; setCookie(key, '', options); return !(readCookie(key)); };
{ parts = cookies[i].split('='); name = parts.shift(); value = parts.join('='); if (key && key === name) { return value; } if (key === undefined) { result[name] = value; } }
conditional_block
cookies.js
SIN.setCookie = function (key, value, options) { options = options || {};
} document.cookie = [ encodeURIComponent(key), '=', encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secur...
value = value || ''; if (typeof options.expires === 'number') { var ms = options.expires * 1000 * 60 * 60 * 24; options.expires = new Date(Date.now() + ms);
random_line_split
add_metadata.rs
use super::Batch; use super::act::Act; use super::iterator::*; use super::packet_batch::PacketBatch; use common::*; use interface::Packet; use interface::PacketTx; use std::marker::PhantomData; pub type MetadataFn<T, M, M2> = Box<FnMut(&Packet<T, M>) -> M2 + Send>; pub struct AddMetadataBatch<M, V> where M: Send ...
}
{ self.parent.get_task_dependencies() }
identifier_body
add_metadata.rs
use super::Batch; use super::act::Act; use super::iterator::*; use super::packet_batch::PacketBatch; use common::*; use interface::Packet; use interface::PacketTx; use std::marker::PhantomData; pub type MetadataFn<T, M, M2> = Box<FnMut(&Packet<T, M>) -> M2 + Send>; pub struct AddMetadataBatch<M, V> where M: Send ...
(&mut self) -> usize { self.parent.start() } #[inline] unsafe fn next_payload(&mut self, idx: usize) -> Option<PacketDescriptor<V::Header, M>> { self.parent.next_payload(idx).map(|p| PacketDescriptor { packet: p.packet.reinterpret_metadata(), }) } } impl<M, V> Act f...
start
identifier_name
add_metadata.rs
use super::Batch; use super::act::Act; use super::iterator::*; use super::packet_batch::PacketBatch; use common::*; use interface::Packet; use interface::PacketTx; use std::marker::PhantomData; pub type MetadataFn<T, M, M2> = Box<FnMut(&Packet<T, M>) -> M2 + Send>; pub struct AddMetadataBatch<M, V> where M: Send ...
} }
#[inline] fn get_task_dependencies(&self) -> Vec<usize> { self.parent.get_task_dependencies()
random_line_split
add_metadata.rs
use super::Batch; use super::act::Act; use super::iterator::*; use super::packet_batch::PacketBatch; use common::*; use interface::Packet; use interface::PacketTx; use std::marker::PhantomData; pub type MetadataFn<T, M, M2> = Box<FnMut(&Packet<T, M>) -> M2 + Send>; pub struct AddMetadataBatch<M, V> where M: Send ...
} #[inline] fn done(&mut self) { self.applied = false; self.parent.done(); } #[inline] fn send_q(&mut self, port: &PacketTx) -> Result<u32> { self.parent.send_q(port) } #[inline] fn capacity(&self) -> i32 { self.parent.capacity() } #[inlin...
{ self.parent.act(); { let iter = PayloadEnumerator::<V::Header, V::Metadata>::new(&mut self.parent); while let Some(ParsedDescriptor { mut packet, .. }) = iter.next(&mut self.parent) { let metadata = (self.generator)(&packet); ...
conditional_block
lib.rs
. Prisma follows a model //! of "opt-in" complexity, meaning that if you just want a library to convert from Rgb to Hsv and back, //! prisma will let you do it with minimal knowledge of color science. If you need to access the CIE spaces //! or do color space conversions however, prisma also provides that functionality...
//! * **[`Xyz`](struct.Xyz.html)** - The "parent" absolute color space other color spaces are defined in terms of //! * **[`Lms`](lms/struct.Lms.html)** - A color space simulating human cone response //! * **[`Lab`](struct.Lab.html)** - A uniform perception color space transformation of XYZ //! * **[`Lchab`](struct.Lch...
random_line_split
conic.rs
derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, MallocSizeOf, PartialEq)] pub struct ConicGradientParams { pub angle: f32, // in radians pub start_offset: f32, pub end_offset: f32, } impl Eq for ConicGradientParams {} impl hash::Hash for ConicGradientParams...
} } /// Identifying key for a line decoration. #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, Eq, PartialEq, Hash, MallocSizeOf)] pub struct ConicGradientKey { pub common: PrimKeyCommonData, pub extend_mode: ExtendMode, pu...
self.angle.to_bits().hash(state); self.start_offset.to_bits().hash(state); self.end_offset.to_bits().hash(state);
random_line_split
conic.rs
(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, MallocSizeOf, PartialEq)] pub struct ConicGradientParams { pub angle: f32, // in radians pub start_offset: f32, pub end_offset: f32, } impl Eq for ConicGradientParams {} impl hash::Hash for ConicGradientParams { ...
// Attempt to detect some of the common configurations with hard gradient stops. Allow // those a higher maximum resolution to avoid the worst cases of aliasing artifacts with // large conic gradients. A better solution would be to go back to rendering very large // conic gradients via...
{ (a - b).abs() < 0.01 }
identifier_body
conic.rs
(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, MallocSizeOf, PartialEq)] pub struct ConicGradientParams { pub angle: f32, // in radians pub start_offset: f32, pub end_offset: f32, } impl Eq for ConicGradientParams {} impl hash::Hash for ConicGradientParams { ...
} prev_stop = Some(stop.offset); } let max_size = if has_hard_stops { 2048.0 } else { 1024.0 }; // Avoid rendering enormous gradients. Radial gradients are mostly made of soft transitions, // so it is unlikely that render...
{ // a is the angle of the stop normalized into 0-1 space and repeating in the 0-0.25 range. // If close to 0.0 or 0.25 it means the stop is vertical or horizontal. For those, the lower // resolution isn't a big issue. let a = item.params.a...
conditional_block
conic.rs
: PrimTemplateCommonData, pub extend_mode: ExtendMode, pub center: DevicePoint, pub params: ConicGradientParams, pub task_size: DeviceIntSize, pub scale: DeviceVector2D, pub stretch_size: LayoutSize, pub tile_spacing: LayoutSize, pub brush_segments: Vec<BrushSegment>, pub stops_opaci...
ConicGradientTask
identifier_name
test_error.py
# pylint: disable-all import unittest from circleci.error import CircleCIException, BadKeyError, BadVerbError, InvalidFilterError class TestCircleCIError(unittest.TestCase): def setUp(self):
def test_error_implements_str(self): self.assertTrue(self.base.__str__ is not object.__str__) string = self.base.__str__() self.assertIn('invalid', string) def test_verb_message(self): self.assertIn('DELETE', self.verb.message) def test_key_message(self): self.ass...
self.base = CircleCIException('fake') self.key = BadKeyError('fake') self.verb = BadVerbError('fake') self.filter = InvalidFilterError('fake', 'status') self.afilter = InvalidFilterError('fake', 'artifacts')
identifier_body
test_error.py
# pylint: disable-all import unittest from circleci.error import CircleCIException, BadKeyError, BadVerbError, InvalidFilterError class TestCircleCIError(unittest.TestCase): def setUp(self): self.base = CircleCIException('fake') self.key = BadKeyError('fake') self.verb = BadVerbError('fa...
(self): self.assertIn('running', self.filter.message) self.assertIn('completed', self.afilter.message)
test_filter_message
identifier_name
test_error.py
# pylint: disable-all import unittest from circleci.error import CircleCIException, BadKeyError, BadVerbError, InvalidFilterError class TestCircleCIError(unittest.TestCase): def setUp(self): self.base = CircleCIException('fake') self.key = BadKeyError('fake') self.verb = BadVerbError('fa...
self.assertIn('running', self.filter.message) self.assertIn('completed', self.afilter.message)
random_line_split
subprocess_handler.py
3 of the License, or # (at your option) any later version. # # DreamPie is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have...
return True def send_object(self, obj): """Send an object to the subprocess""" if self._popen is None: raise ValueError("Subprocess not living") send_object(self._sock, obj) def wait_for_object(self, timeout_s): """ Wait for timeout_s seconds or un...
self._on_object_recv(obj)
conditional_block
subprocess_handler.py
3 of the License, or # (at your option) any later version. # # DreamPie is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have...
def recv_object(self): """Wait for an object from the subprocess and return it""" if self._popen is None: raise ValueError("Subprocess not living") return recv_object(self._sock) def write(self, data): """Write data to stdin""" if self._popen is None: ...
""" Wait for timeout_s seconds or until the socket is ready for reading. Return True if an object was received, and False if the timeout expired. """ return len(select([self._sock], [], [], timeout_s)[0]) > 0
identifier_body
subprocess_handler.py
3 of the License, or # (at your option) any later version. # # DreamPie is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have...
(StartError): """Start subprocess failed because process terminated.""" def __init__(self, rc, output): self.rc = rc self.output = output def __str__(self): r = _("Subprocess terminated with return code %d.") % self.rc if self.output: r += _("\nSubprocess wrote:\n...
StartTerminatedError
identifier_name
subprocess_handler.py
3 of the License, or # (at your option) any later version. # # DreamPie is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should hav...
if self.output: r += _("\nSubprocess wrote:\n%s") % self.output return r class SubprocessHandler(object): """ Manage interaction with the subprocess. The communication, besides stdout, stderr and stdin, goes like this: You can call a function, and get a return value. (Th...
r = _("Subprocess didn't call back in %s seconds. " "This may be caused by a firewall program blocking the " "communication between the main process and the subproces." ) % self.timeout
random_line_split
robotic_arm.py
_offset_mm = 50 vertical_arm_mm = 100 horizontal_arm_mm = 100 level_arm_len= 20 claw_offset_to_center = 10 small_cup_positions = [(100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), ...
# Rail stepper and base servo have been adjusted as necessary. This function # Adjusts the three servos Vertical, Horizontal and Level servos to get the # required Z and X from to_pos. def execute_move_claw_xz(self, to_pos): from_pos = (self.vertical_servo.get_current_pos(), self.horizonta...
self.tipping_servo.move_to(0)
identifier_body
robotic_arm.py
_offset_mm = 50 vertical_arm_mm = 100 horizontal_arm_mm = 100 level_arm_len= 20 claw_offset_to_center = 10 small_cup_positions = [(100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), ...
# Need to rotate base servo to point from (0,curr_pos[1]) to (dest_pos[0],dest_pos[1]) # degrees to rotate clockwise with 0 pointing along x axis towards containers degrees = degrees(atan(float(curr_y_pos - dest_pos[1]) /float(0 - dest_pos[0]))) if (degrees < 0 or de...
curr_y_pos = self.rail.get_curr_pos_mm()
random_line_split
robotic_arm.py
_offset_mm = 50 vertical_arm_mm = 100 horizontal_arm_mm = 100 level_arm_len= 20 claw_offset_to_center = 10 small_cup_positions = [(100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), ...
(self, dest_pos): self.at_base = False self.rail.move_to(max(0, min(RoboticArm.max_rail_translation_mm, dest_pos[1]))) curr_y_pos = self.rail.get_curr_pos_mm() # Need to rotate base servo to point from (0,curr_pos[1]) to (dest_pos[0],dest_pos[1]) # degrees to rotate clockwise with 0 pointing along x...
move_rail_rotate_base
identifier_name
robotic_arm.py
_offset_mm = 50 vertical_arm_mm = 100 horizontal_arm_mm = 100 level_arm_len= 20 claw_offset_to_center = 10 small_cup_positions = [(100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), (100, 0, 30, 30, 30), ...
# Positions of the various servos. desired_servo_pos = RoboticArm.utensil_positions_size[utensil_size] self.execute_move_claw_xz(desired_servo_pos) self.rail.move_to(desired_servo_pos[0]) self.base_servo.move_to(desired_servo_pos[1]) self.at_base = False def move_to_base(self): self.exec...
raise ValueError("Invalid utensil size:" + utensil_size)
conditional_block
rsvp.js
import * as RSVP from 'rsvp'; import { backburner, _rsvpErrorQueue } from '@ember/runloop'; import { getDispatchOverride } from '@ember/-internals/error-handling'; import { assert } from '@ember/debug'; RSVP.configure('async', (callback, promise) => { backburner.schedule('actions', null, callback, promise); }); RSV...
(reason) { if (!reason) return; if (reason.errorThrown) { return unwrapErrorThrown(reason); } if (reason.name === 'UnrecognizedURLError') { assert(`The URL '${reason.message}' did not match any routes in your application`, false); return; } if (reason.name === 'TransitionAborted') { retur...
errorFor
identifier_name
rsvp.js
import * as RSVP from 'rsvp'; import { backburner, _rsvpErrorQueue } from '@ember/runloop'; import { getDispatchOverride } from '@ember/-internals/error-handling'; import { assert } from '@ember/debug'; RSVP.configure('async', (callback, promise) => { backburner.schedule('actions', null, callback, promise); }); RSV...
export default RSVP;
{ let error = reason.errorThrown; if (typeof error === 'string') { error = new Error(error); } Object.defineProperty(error, '__reason_with_error_thrown__', { value: reason, enumerable: false, }); return error; }
identifier_body
rsvp.js
import * as RSVP from 'rsvp'; import { backburner, _rsvpErrorQueue } from '@ember/runloop'; import { getDispatchOverride } from '@ember/-internals/error-handling'; import { assert } from '@ember/debug'; RSVP.configure('async', (callback, promise) => { backburner.schedule('actions', null, callback, promise); }); RSV...
return; } return reason; } function unwrapErrorThrown(reason) { let error = reason.errorThrown; if (typeof error === 'string') { error = new Error(error); } Object.defineProperty(error, '__reason_with_error_thrown__', { value: reason, enumerable: false, }); return error; } export defa...
assert(`The URL '${reason.message}' did not match any routes in your application`, false); return; } if (reason.name === 'TransitionAborted') {
random_line_split
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//! The prelude is primarily concerned with exporting *traits* that are so //! pervasive that it would be obnoxious to import for every use, particularly //! those that define methods on primitive types. #![stable(feature = "rust1", since = "1.0.0")] pub mod v1;
//! //! ```ignore //! use std::prelude::v1::*; //! ``` //!
random_line_split
Rc.py
from Components.Pixmap import MovingPixmap, MultiPixmap from Tools.Directories import resolveFilename, SCOPE_SKIN from xml.etree.ElementTree import ElementTree from Components.config import config, ConfigInteger from Components.RcModel import rc_model from boxbranding import getBoxType config.misc.rcused = Config...
(self, key): if self.isDefaultRc: rc = self.rcs[config.misc.rcused.value] else: try: rc = self.rcs[2] except: rc = self.rcs[config.misc.rcused.value] if rc.has_key(key): rcpos = self['rc'].getPosition() ...
selectKey
identifier_name
Rc.py
from Components.Pixmap import MovingPixmap, MultiPixmap from Tools.Directories import resolveFilename, SCOPE_SKIN from xml.etree.ElementTree import ElementTree from Components.config import config, ConfigInteger from Components.RcModel import rc_model from boxbranding import getBoxType config.misc.rcused = Config...
self['rc'].setPixmapNum(config.misc.rcused.value) else: self['rc'].setPixmapNum(0) def readPositions(self): if self.isDefaultRc: target = resolveFilename(SCOPE_SKIN, 'rcpositions.xml') else: target = rc_model.getRcLocation() + 'rcposit...
if getBoxType() in ('uniboxhd1', 'uniboxhd2', 'uniboxhd3', 'sezam5000hd', 'mbtwin', 'beyonwizt3'): self['rc'].setPixmapNum(config.misc.rcused.value) elif self.isDefaultRc:
random_line_split
Rc.py
from Components.Pixmap import MovingPixmap, MultiPixmap from Tools.Directories import resolveFilename, SCOPE_SKIN from xml.etree.ElementTree import ElementTree from Components.config import config, ConfigInteger from Components.RcModel import rc_model from boxbranding import getBoxType config.misc.rcused = Config...
def readPositions(self): if self.isDefaultRc: target = resolveFilename(SCOPE_SKIN, 'rcpositions.xml') else: target = rc_model.getRcLocation() + 'rcpositions.xml' tree = ElementTree(file=target) rcs = tree.getroot() self.rcs = {} for...
self['rc'].setPixmapNum(0)
conditional_block