file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
cache.py
""" Caching facility for SymPy """ # TODO: refactor CACHE & friends into class? # global cache registry: CACHE = [] # [] of # (item, {} or tuple of {}) from sympy.core.decorators import wraps def print_cache(): """print cache content""" for item, cache in CACHE: item = str(item) ...
print ' %s :\t%s' % (k, v) def clear_cache(): """clear cache content""" for item, cache in CACHE: if not isinstance(cache, tuple): cache = (cache,) for kv in cache: kv.clear() ######################################## def __cacheit_nocache(func): r...
random_line_split
cache.py
""" Caching facility for SymPy """ # TODO: refactor CACHE & friends into class? # global cache registry: CACHE = [] # [] of # (item, {} or tuple of {}) from sympy.core.decorators import wraps def print_cache(): """print cache content""" for item, cache in CACHE: item = str(item) ...
(key, default=None): from os import getenv return getenv(key, default) # SYMPY_USE_CACHE=yes/no/debug USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower() if USE_CACHE == 'no': cacheit = __cacheit_nocache elif USE_CACHE == 'yes': cacheit = __cacheit elif USE_CACHE == 'debug': cacheit = __cache...
_getenv
identifier_name
icmp.py
# $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $ from dpkt import Packet, in_cksum as _icmp_cksum import ip # Types (icmp_type) and codes (icmp_code) - # http://www.iana.org/assignments/icmp-parameters ICMP_CODE_NONE = 0 # for types without codes ICMP_ECHOREPLY = 0 # echo reply ICMP_UNREACH = 3 # dest u...
_typesw = { 0:Echo, 3:Unreach, 4:Quench, 5:Redirect, 8:Echo, 11:TimeExceed } def unpack(self, buf): Packet.unpack(self, buf) try: self.data = self._typesw[self.type](self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) ...
pass
identifier_body
icmp.py
# $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $ from dpkt import Packet, in_cksum as _icmp_cksum import ip # Types (icmp_type) and codes (icmp_code) - # http://www.iana.org/assignments/icmp-parameters ICMP_CODE_NONE = 0 # for types without codes ICMP_ECHOREPLY = 0 # echo reply ICMP_UNREACH = 3 # dest u...
(Packet): __hdr__ = (('id', 'H', 0), ('seq', 'H', 0)) class Quote(Packet): __hdr__ = (('pad', 'I', 0),) def unpack(self, buf): Packet.unpack(self, buf) self.data = self.ip = ip.IP(self.data) class Unreach(Quote): __hdr__ = (('pad', 'H', 0), ('mtu', 'H', 0)...
Echo
identifier_name
icmp.py
# $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $ from dpkt import Packet, in_cksum as _icmp_cksum import ip # Types (icmp_type) and codes (icmp_code) - # http://www.iana.org/assignments/icmp-parameters ICMP_CODE_NONE = 0 # for types without codes ICMP_ECHOREPLY = 0 # echo reply ICMP_UNREACH = 3 # dest u...
return Packet.__str__(self)
self.sum = _icmp_cksum(Packet.__str__(self))
conditional_block
icmp.py
# $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $ from dpkt import Packet, in_cksum as _icmp_cksum import ip # Types (icmp_type) and codes (icmp_code) - # http://www.iana.org/assignments/icmp-parameters ICMP_CODE_NONE = 0 # for types without codes ICMP_ECHOREPLY = 0 # echo reply ICMP_UNREACH = 3 # dest u...
def unpack(self, buf): Packet.unpack(self, buf) try: self.data = self._typesw[self.type](self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except: self.data = buf def __str__(self): if not self.sum: self.sum...
random_line_split
dst-bad-coerce4.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 ...
pub fn main() { // With a vec of isizes. let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] }; let f2: &Fat<[isize; 3]> = f1; //~^ ERROR mismatched types //~| expected type `&Fat<[isize; 3]>` //~| found type `&Fat<[isize]>` //~| expected array of 3 elements, found slice // Tuple with a vec o...
ptr: T }
random_line_split
dst-bad-coerce4.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 ...
() { // With a vec of isizes. let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] }; let f2: &Fat<[isize; 3]> = f1; //~^ ERROR mismatched types //~| expected type `&Fat<[isize; 3]>` //~| found type `&Fat<[isize]>` //~| expected array of 3 elements, found slice // Tuple with a vec of isizes. ...
main
identifier_name
dst-bad-coerce4.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 ...
{ // With a vec of isizes. let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] }; let f2: &Fat<[isize; 3]> = f1; //~^ ERROR mismatched types //~| expected type `&Fat<[isize; 3]>` //~| found type `&Fat<[isize]>` //~| expected array of 3 elements, found slice // Tuple with a vec of isizes. ...
identifier_body
test_volumes_get.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
(base.BaseVolumeV1Test): _interface = "json" @classmethod def setUpClass(cls): super(VolumesGetTest, cls).setUpClass() cls.client = cls.volumes_client def _delete_volume(self, volume_id): resp, _ = self.client.delete_volume(volume_id) self.assertEqual(202, resp.status) ...
VolumesGetTest
identifier_name
test_volumes_get.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
new_desc = 'This is the new description of volume' resp, update_volume = \ self.client.update_volume(volume['id'], display_name=new_v_name, display_description=new_desc) # Assert response body for update_volu...
self.assertEqual(boot_flag, False) # Update Volume new_v_name = data_utils.rand_name('new-Volume')
random_line_split
test_volumes_get.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
@attr(type='gate') def test_volume_get_metadata_none(self): # Create a volume without passing metadata, get details, and delete # Create a volume without metadata volume = self.create_volume(metadata={}) # GET Volume resp, fetched_volume = self.client.get_volume(volum...
volume = {} v_name = data_utils.rand_name('Volume') metadata = {'Type': 'Test'} # Create a volume resp, volume = self.client.create_volume(size=1, display_name=v_name, metadata=metadata, ...
identifier_body
test_volumes_get.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
if 'imageRef' not in kwargs: self.assertEqual(boot_flag, False) # Update Volume new_v_name = data_utils.rand_name('new-Volume') new_desc = 'This is the new description of volume' resp, update_volume = \ self.client.update_volume(volume['id'], ...
self.assertEqual(boot_flag, True)
conditional_block
index.ts
export { FilterService } from './app/services/filter.service'; export { WorkItemType } from './app/models/work-item-type'; export {
export { WorkItemService } from './app/services/work-item.service'; export { WorkItem } from './app/models/work-item'; export { PlannerModule } from './planner.module'; export { WorkItemDetailExternalModule as PlannerDetailModule, } from './app/components_ngrx/work-item-detail/work-item-detail-external.module'; exp...
WorkItemDetailModule, } from './app/components_ngrx/work-item-detail/work-item-detail.module';
random_line_split
mod.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 ...
{ entry: CFGIndex, exit: CFGIndex, } impl CFG { pub fn new(tcx: &ty::ctxt, blk: &ast::Block) -> CFG { construct::construct(tcx, blk) } }
CFGIndices
identifier_name
mod.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 ...
*/ #![allow(dead_code)] // still a WIP, #6298 use middle::graph; use middle::ty; use syntax::ast; use util::nodemap::NodeMap; mod construct; pub mod graphviz; pub struct CFG { pub exit_map: NodeMap<CFGIndex>, pub graph: CFGGraph, pub entry: CFGIndex, pub exit: CFGIndex, } pub struct CFGNodeData { ...
random_line_split
bindAll.js
'use strict';
func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2JpbmRBbGwuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxJQUFJLFVBQVUsUUFBUSxXQUFSLENBQWQ7SUFDSSxPQUFPLFFBQVEsU0FBUixFQ...
var convert = require('./convert'), func = convert('bindAll', require('../bindAll'));
random_line_split
popupmenu.js
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed ...
* * @param {Element} element Element whose click event should trigger the menu. * @param {goog.positioning.Corner} opt_targetCorner Corner of the target that * the menu should be anchored to. * @param {goog.positioning.Corner} opt_menuCorner Corner of the menu that * should be anchored. * @param {boolean...
* multiple positions doesn't make sense.
random_line_split
popupmenu.js
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed ...
}; /** * Creates an object describing how the popup menu should be attached to the * anchoring element based on the given parameters. The created object is * stored, keyed by {@code element} and is retrievable later by invoking * {@link #getAttachTarget(element)} at a later point. * * Subclass may add more pro...
{ this.attachEvent_(target); }
conditional_block
core.js
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
else if (isArrayBuffer(arg)) { init.call(this, pdfManager, new Stream(arg), password); } else { error('PDFDocument: Unknown argument type'); } } function init(pdfManager, stream, password) { assert(stream.length > 0, 'stream must have data'); this.pdfManager = pdfManager; this.stre...
{ init.call(this, pdfManager, arg, password); }
conditional_block
core.js
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
, get rotate() { var rotate = this.getInheritedPageProp('Rotate') || 0; // Normalize rotation so it's a multiple of 90 and between 0 and 270 if (rotate % 90 !== 0) { rotate = 0; } else if (rotate >= 360) { rotate = rotate % 360; } else if (rotate < 0) { // The ...
{ var mediaBox = this.mediaBox; var cropBox = this.getInheritedPageProp('CropBox'); if (!isArray(cropBox) || cropBox.length !== 4) { return shadow(this, 'view', mediaBox); } // From the spec, 6th ed., p.963: // "The crop, bleed, trim, and art boxes should not ordinarily ...
identifier_body
core.js
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
() { var obj = this.getInheritedPageProp('MediaBox'); // Reset invalid media box to letter size. if (!isArray(obj) || obj.length !== 4) { obj = LETTER_SIZE_MEDIABOX; } return shadow(this, 'mediaBox', obj); }, get view() { var mediaBox = this.mediaBox; var cropB...
mediaBox
identifier_name
core.js
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
} else { error('PDFDocument: Unknown argument type'); } } function init(pdfManager, stream, password) { assert(stream.length > 0, 'stream must have data'); this.pdfManager = pdfManager; this.stream = stream; var xref = new XRef(this.stream, password, pdfManager); this.xref = xref;...
init.call(this, pdfManager, arg, password); } else if (isArrayBuffer(arg)) { init.call(this, pdfManager, new Stream(arg), password);
random_line_split
create_changeset.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::{BTreeMap, BTreeSet}; use bytes::Bytes; use changesets::ChangesetsRef; use chrono::{DateTime, FixedOffset}; use cont...
}
{ let allowed_no_parents = self .config() .source_control_service .permit_commits_without_parents; let valid_parent_count = parents.len() == 1 || (parents.len() == 0 && allowed_no_parents); // Merge rules are not validated yet, so only a single parent is suppo...
identifier_body
create_changeset.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::{BTreeMap, BTreeSet}; use bytes::Bytes; use changesets::ChangesetsRef; use chrono::{DateTime, FixedOffset}; use cont...
let parent_ctxs: Vec<_> = parents .iter() .map(|parent_id| async move { let parent_ctx = self .changeset(ChangesetSpecifier::Bonsai(parent_id.clone())) .await? .ok_or_else(|| { MononokeErr...
// Obtain contexts for each of the parents (which should exist).
random_line_split
create_changeset.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::{BTreeMap, BTreeSet}; use bytes::Bytes; use changesets::ChangesetsRef; use chrono::{DateTime, FixedOffset}; use cont...
( &self, parents: Vec<ChangesetId>, author: String, author_date: DateTime<FixedOffset>, committer: Option<String>, committer_date: Option<DateTime<FixedOffset>>, message: String, extra: BTreeMap<String, Vec<u8>>, changes: BTreeMap<MononokePath, Cre...
create_changeset
identifier_name
test_install_suse.py
""" Tests for install.py for SUSE based Linux distributions """ import os import shutil from unittest import mock import pytest from install import Cmd, CmdError, RemoteFileNotFoundError pytestmark = pytest.mark.skipif( not pytest.helpers.helper_is_suse(), reason="Tests for openSUSE/SUSE" ) def
(sys_rpm): with mock.patch.object(Cmd, 'sh_e') as mock_sh_e: ce = CmdError('test.') ce.stderr = 'Package \'dummy\' not found.\n' mock_sh_e.side_effect = ce with pytest.raises(RemoteFileNotFoundError) as exc: sys_rpm.download('dummy') assert mock_sh_e.called ...
test_rpm_download_raise_not_found_error
identifier_name
test_install_suse.py
""" Tests for install.py for SUSE based Linux distributions """ import os import shutil from unittest import mock import pytest from install import Cmd, CmdError, RemoteFileNotFoundError pytestmark = pytest.mark.skipif( not pytest.helpers.helper_is_suse(), reason="Tests for openSUSE/SUSE" ) def test_rpm_do...
@pytest.mark.network def test_app_verify_system_status_is_ok_on_sys_rpm_and_missing_pkgs(app): app.linux.rpm.is_system_rpm = mock.MagicMock(return_value=True) app.linux.verify_system_status()
sys_rpm.arch = 'x86_64' with pytest.helpers.work_dir(): for rpm_file in rpm_files: shutil.copy(rpm_file, '.') sys_rpm.extract('rpm-build-libs') files = os.listdir('./usr/lib64') files.sort() assert files == [ 'librpmbuild.so.7', 'librpmbui...
identifier_body
test_install_suse.py
""" Tests for install.py for SUSE based Linux distributions """ import os import shutil from unittest import mock import pytest from install import Cmd, CmdError, RemoteFileNotFoundError
def test_rpm_download_raise_not_found_error(sys_rpm): with mock.patch.object(Cmd, 'sh_e') as mock_sh_e: ce = CmdError('test.') ce.stderr = 'Package \'dummy\' not found.\n' mock_sh_e.side_effect = ce with pytest.raises(RemoteFileNotFoundError) as exc: sys_rpm.download('d...
pytestmark = pytest.mark.skipif( not pytest.helpers.helper_is_suse(), reason="Tests for openSUSE/SUSE" )
random_line_split
test_install_suse.py
""" Tests for install.py for SUSE based Linux distributions """ import os import shutil from unittest import mock import pytest from install import Cmd, CmdError, RemoteFileNotFoundError pytestmark = pytest.mark.skipif( not pytest.helpers.helper_is_suse(), reason="Tests for openSUSE/SUSE" ) def test_rpm_do...
sys_rpm.extract('rpm-build-libs') files = os.listdir('./usr/lib64') files.sort() assert files == [ 'librpmbuild.so.7', 'librpmbuild.so.7.0.1', 'librpmsign.so.7', 'librpmsign.so.7.0.1', ] @pytest.mark.network def test_app_verify_...
shutil.copy(rpm_file, '.')
conditional_block
generic-arg-mismatch-recover.rs
// Copyright 2018 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 ...
() { Foo::<'static, 'static, ()>(&0); //~ ERROR wrong number of lifetime arguments //~^ ERROR mismatched types Bar::<'static, 'static, ()>(&()); //~ ERROR wrong number of lifetime arguments //~^ ERROR wrong number of type arguments }
main
identifier_name
generic-arg-mismatch-recover.rs
// Copyright 2018 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 main() { Foo::<'static, 'static, ()>(&0); //~ ERROR wrong number of lifetime arguments //~^ ERROR mismatched types Bar::<'static, 'static, ()>(&()); //~ ERROR wrong number of lifetime arguments //~^ ERROR wrong number of type arguments }
struct Bar<'a>(&'a ());
random_line_split
stock.py
import numpy as np class Stock: """ Class to represent the data and ratios of a stock. """ def __init__(self, eps, dps, roe=0): ''' eps: earnings per share. dps: dividends per share. roe: fractional return on equity, default to 0. ''' self.eps = n...
def growth_rate(self): ''' Calculates the dividend growth rate: (1 - payout ratio)^cost of equity Returns the fractional expected growth rate numpy array. ''' ones = np.ones_like(self.roe) return (ones - self.payout_rati...
''' Calculates the stock payout ratio based on: Returns fractional payout ratio numpy array. ''' return 1 / self.retention_ratio()
identifier_body
stock.py
import numpy as np class Stock: """ Class to represent the data and ratios of a stock. """ def __init__(self, eps, dps, roe=0): ''' eps: earnings per share. dps: dividends per share. roe: fractional return on equity, default to 0. ''' self.eps = n...
(self): ''' Calculates the dividend growth rate: (1 - payout ratio)^cost of equity Returns the fractional expected growth rate numpy array. ''' ones = np.ones_like(self.roe) return (ones - self.payout_ratio()) * self.roe
growth_rate
identifier_name
stock.py
import numpy as np class Stock: """ Class to represent the data and ratios of a stock. """
def __init__(self, eps, dps, roe=0): ''' eps: earnings per share. dps: dividends per share. roe: fractional return on equity, default to 0. ''' self.eps = np.array(eps).astype(float) self.dps = np.array(dps).astype(float) self.roe = np.array(ro...
random_line_split
partitioner.py
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Univ...
(self): """ Return a string representation of the partitioner, the list of fuzzy sets and their parameters :return: """ tmp = self.name + ":\n" for key in self.sets.keys(): tmp += str(self.sets[key])+ "\n" return tmp def __len__(self): ""...
__str__
identifier_name
partitioner.py
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Univ...
def search(self, data, **kwargs): """ Perform a search for the nearest fuzzy sets of the point 'data'. This function were designed to work with several overlapped fuzzy sets. :param data: the value to search for the nearest fuzzy sets :param type: the return type: 'index' ...
""" Check if the input data is outside the known Universe of Discourse and, if it is, round it to the closest fuzzy set. :param data: input data to be verified :return: the index of the closest fuzzy set when data is outside de universe of discourse or None if the data is inside...
identifier_body
partitioner.py
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Univ...
self.kdtree = KDTree(points) sys.setrecursionlimit(1000) def fuzzyfy(self, data, **kwargs): """ Fuzzyfy the input data according to this partitioner fuzzy sets. :param data: input value to be fuzzyfied :keyword alpha_cut: the minimal membership value to be consider...
#self.index[ct] = fset.name import sys sys.setrecursionlimit(100000)
random_line_split
partitioner.py
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Univ...
def plot(self, ax, rounding=0): """ Plot the partitioning using the Matplotlib axis ax :param ax: Matplotlib axis """ ax.set_title(self.name) ax.set_ylim([0, 1.1]) ax.set_xlim([self.min, self.max]) ticks = [] x = [] for key in self....
return sorted(ix)
conditional_block
LookDetail.js
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookC...
}); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyC...
{ if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ ...
identifier_body
LookDetail.js
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookC...
} var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next...
animating: false, next:false, }); return;
random_line_split
LookDetail.js
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookC...
return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> ...
{ return false; }
conditional_block
LookDetail.js
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookC...
(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> ...
renderRow
identifier_name
verify.py
import calendar import json from datetime import datetime from time import gmtime, time from urlparse import parse_qsl, urlparse from wsgiref.handlers import format_date_time import jwt from browserid.errors import ExpiredSignatureError from django_statsd.clients import statsd from receipts import certs from lib.cef_...
status, body = receipt_check(environ) start_response(status_codes[status], get_headers(len(body))) return [body]
else: # Only allow POST through as per spec. if environ.get('REQUEST_METHOD') != 'POST': status = 405 else:
random_line_split
verify.py
import calendar import json from datetime import datetime from time import gmtime, time from urlparse import parse_qsl, urlparse from wsgiref.handlers import format_date_time import jwt from browserid.errors import ExpiredSignatureError from django_statsd.clients import statsd from receipts import certs from lib.cef_...
try: conn = mypool.connect() cursor = conn.cursor() cursor.execute('SELECT id FROM users_install ORDER BY id DESC LIMIT 1') except Exception, err: return 500, str(err) return 200, output def receipt_check(environ): output = '' with statsd.timer('services.verify')...
return 500, 'SIGNING_SERVER_ACTIVE is not set'
conditional_block
verify.py
import calendar import json from datetime import datetime from time import gmtime, time from urlparse import parse_qsl, urlparse from wsgiref.handlers import format_date_time import jwt from browserid.errors import ExpiredSignatureError from django_statsd.clients import statsd from receipts import certs from lib.cef_...
(self, raise_exception=True): """ Attempt to retrieve the app id from the storedata in the receipt. """ try: return int(self.get_storedata()['id']) except Exception, e: if raise_exception: # There was some value for storedata but it was inv...
get_app_id
identifier_name
verify.py
import calendar import json from datetime import datetime from time import gmtime, time from urlparse import parse_qsl, urlparse from wsgiref.handlers import format_date_time import jwt from browserid.errors import ExpiredSignatureError from django_statsd.clients import statsd from receipts import certs from lib.cef_...
def check_purchase_app(self): """ Verifies that the app has been purchased by the user. """ self.setup_db() sql = """SELECT type FROM addon_purchase WHERE addon_id = %(app_id)s AND uuid = %(uuid)s LIMIT 1;""" self.cursor.execute(sql...
if contribution_inapp_id != self.get_inapp_id(): log_info('Invalid receipt, inapp_id does not match') raise InvalidReceipt('NO_PURCHASE')
identifier_body
log.py
import logging, sys from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL class InfoFilter(logging.Filter): def filter(self, rec): return rec.levelno in (logging.DEBUG, logging.INFO) def _new_custom_logger(name='BiblioPixel', fmt='%(levelname)s - %(module)s - %(message)s'): ...
return logger logger = _new_custom_logger() setLogLevel = logger.setLevel debug, info, warning, error, critical, exception = ( logger.debug, logger.info, logger.warning, logger.error, logger.critical, logger.exception)
logger.setLevel(logging.INFO) h1 = logging.StreamHandler(sys.stdout) h1.setLevel(logging.DEBUG) h1.addFilter(InfoFilter()) h1.setFormatter(formatter) h2 = logging.StreamHandler(sys.stderr) h2.setLevel(logging.WARNING) h2.setFormatter(formatter) logger.ad...
conditional_block
log.py
import logging, sys from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL class InfoFilter(logging.Filter): def filter(self, rec):
def _new_custom_logger(name='BiblioPixel', fmt='%(levelname)s - %(module)s - %(message)s'): logger = logging.getLogger(name) formatter = logging.Formatter(fmt=fmt) if len(logger.handlers) == 0: logger.setLevel(logging.INFO) h1 = logging.StreamHandler(sys.stdout) ...
return rec.levelno in (logging.DEBUG, logging.INFO)
identifier_body
log.py
import logging, sys from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL class InfoFilter(logging.Filter): def
(self, rec): return rec.levelno in (logging.DEBUG, logging.INFO) def _new_custom_logger(name='BiblioPixel', fmt='%(levelname)s - %(module)s - %(message)s'): logger = logging.getLogger(name) formatter = logging.Formatter(fmt=fmt) if len(logger.handlers) == 0: logger....
filter
identifier_name
log.py
import logging, sys from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL class InfoFilter(logging.Filter): def filter(self, rec): return rec.levelno in (logging.DEBUG, logging.INFO) def _new_custom_logger(name='BiblioPixel', fmt='%(levelname)s - %(module)s - %(message)s'): ...
logger = _new_custom_logger() setLogLevel = logger.setLevel debug, info, warning, error, critical, exception = ( logger.debug, logger.info, logger.warning, logger.error, logger.critical, logger.exception)
return logger
random_line_split
music.ts
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // // ## Description // This class implements some standard music theory routines. import { Vex } from './vex'; export interface NoteAccidental { note: number; accidental: AccidentalValue; } export interface NoteParts { root: string; accid...
}
{ const keySigParts = this.getKeyParts(keySignature); if (!keySigParts.type) throw new Vex.RERR('BadArguments', 'Unsupported key type: undefined'); const scaleName = Music.scaleTypes[keySigParts.type]; let keySigString = keySigParts.root; if (keySigParts.accidental) keySigString += keySigParts.acci...
identifier_body
music.ts
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // // ## Description // This class implements some standard music theory routines. import { Vex } from './vex'; export interface NoteAccidental { note: number; accidental: AccidentalValue; } export interface NoteParts { root: string; accid...
(): string[] { return ['bb', 'b', 'n', '#', '##']; } static get noteValues(): Record<string, Key> { return { c: { root_index: 0, int_val: 0 }, cn: { root_index: 0, int_val: 0 }, 'c#': { root_index: 0, int_val: 1 }, 'c##': { root_index: 0, int_val: 2 }, cb: { root_index: 0, int...
accidentals
identifier_name
music.ts
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // // ## Description // This class implements some standard music theory routines. import { Vex } from './vex'; export interface NoteAccidental { note: number; accidental: AccidentalValue; } export interface NoteParts { root: string; accid...
else { throw new Vex.RERR('BadArguments', `Invalid key: ${keyString}`); } } getNoteValue(noteString: string): number { const value = Music.noteValues[noteString]; if (value == null) { throw new Vex.RERR('BadArguments', `Invalid note name: ${noteString}`); } return value.int_val; ...
{ const root = match[1]; const accidental = match[2]; let type = match[3]; // Unspecified type implies major if (!type) type = 'M'; return { root, accidental, type, }; }
conditional_block
music.ts
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // // ## Description // This class implements some standard music theory routines. import { Vex } from './vex'; export interface NoteAccidental { note: number; accidental: AccidentalValue; } export interface NoteParts { root: string; accid...
return ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']; } static get diatonic_intervals(): string[] { return ['unison', 'm2', 'M2', 'm3', 'M3', 'p4', 'dim5', 'p5', 'm6', 'M6', 'b7', 'M7', 'octave']; } static get diatonic_accidentals(): Record<string, NoteAccidental> { return { ...
static get canonical_notes(): string[] {
random_line_split
login-form.component.ts
/** * Created by woolfi182 on 06.06.2016. */ import {Component} from '@angular/core'; import {Router} from '@angular/router'; import {AuthService} from "./auth.service"; import {UserService} from "../user/user.service"; @Component({ selector: 'login-form', template: ` <div class="error-message-block fade...
else { this.failedMessage = 'Connection error'; } this.failedAuth = true; }) } }
{ this.failedMessage = 'Invalid login or password'; }
conditional_block
login-form.component.ts
/** * Created by woolfi182 on 06.06.2016. */ import {Component} from '@angular/core'; import {Router} from '@angular/router'; import {AuthService} from "./auth.service"; import {UserService} from "../user/user.service"; @Component({ selector: 'login-form', template: ` <div class="error-message-block fade...
{ user = { login: '', password: '' } private failedMessage = null; private failedAuth = null; constructor(private _authService:AuthService , private _userService:UserService , private _router:Router) { } onSubmit(form) { this.failedAuth = null ...
LoginFormComponent
identifier_name
login-form.component.ts
/** * Created by woolfi182 on 06.06.2016. */ import {Component} from '@angular/core'; import {Router} from '@angular/router'; import {AuthService} from "./auth.service"; import {UserService} from "../user/user.service"; @Component({ selector: 'login-form', template: ` <div class="error-message-block fade...
this.failedAuth = true; }) } }
random_line_split
log_handler.rs
use chrono::{Local, NaiveDate}; use std::collections::HashMap; use std::fs::{create_dir_all, File, OpenOptions}; use std::io; use std::io::Write; use std::path::Path; use std::thread; use tokio::{runtime::Runtime, sync::mpsc::Receiver, task}; use super::log_messages::LogMessage; pub fn create_log_handler(log_dir: Str...
if let Err(error) = file.write_all(log_line.as_bytes()) { println!("Error writing log file: {:?}", error); break; } } println!("Logging disabled."); }) .await .unw...
);
random_line_split
log_handler.rs
use chrono::{Local, NaiveDate}; use std::collections::HashMap; use std::fs::{create_dir_all, File, OpenOptions}; use std::io; use std::io::Write; use std::path::Path; use std::thread; use tokio::{runtime::Runtime, sync::mpsc::Receiver, task}; use super::log_messages::LogMessage; pub fn
(log_dir: String, mut log_rx: Receiver<Box<dyn LogMessage>>) { thread::spawn(move || { let rt = Runtime::new().unwrap(); let local = task::LocalSet::new(); local.block_on(&rt, async move { task::spawn_local(async move { let mut day = Local::today().naive_local(); ...
create_log_handler
identifier_name
log_handler.rs
use chrono::{Local, NaiveDate}; use std::collections::HashMap; use std::fs::{create_dir_all, File, OpenOptions}; use std::io; use std::io::Write; use std::path::Path; use std::thread; use tokio::{runtime::Runtime, sync::mpsc::Receiver, task}; use super::log_messages::LogMessage; pub fn create_log_handler(log_dir: Str...
fn create_log_file(log_dir: &str, log: &str, day: &NaiveDate) -> io::Result<File> { let dir_path = format!("{}/{}", log_dir, day.format("%Y%m%d")); create_dir_all(Path::new(&dir_path))?; let file_path = format!("{}/{}", dir_path, log); OpenOptions::new().create(true).append(true).open(file_path) }
{ thread::spawn(move || { let rt = Runtime::new().unwrap(); let local = task::LocalSet::new(); local.block_on(&rt, async move { task::spawn_local(async move { let mut day = Local::today().naive_local(); let mut log_files: HashMap<String, File> = Ha...
identifier_body
log_handler.rs
use chrono::{Local, NaiveDate}; use std::collections::HashMap; use std::fs::{create_dir_all, File, OpenOptions}; use std::io; use std::io::Write; use std::path::Path; use std::thread; use tokio::{runtime::Runtime, sync::mpsc::Receiver, task}; use super::log_messages::LogMessage; pub fn create_log_handler(log_dir: Str...
} }; let log_line = format!( "{} {}\n", now.format("%H:%M:%S%.3f"), log_message.get_message() ); if let Err(error) = file.write_all(log_line.a...
{ println!("Could not create log file: {:?}", error); break; }
conditional_block
Network.js
// Axios API import axios from 'axios'; import { normalize } from 'normalizr'; import Immutable from 'seamless-immutable'; import { debug } from './utils/Messages'; // eslint-disable-next-line import/prefer-default-export export const api = (schema) => { const instance = axios.create({ headers: { responseType: '...
return Promise.reject({ status: res.status, ...res.data }); } // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject(false); }, ); return instance; };
random_line_split
Network.js
// Axios API import axios from 'axios'; import { normalize } from 'normalizr'; import Immutable from 'seamless-immutable'; import { debug } from './utils/Messages'; // eslint-disable-next-line import/prefer-default-export export const api = (schema) => { const instance = axios.create({ headers: { responseType: '...
if (res) { // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject({ status: res.status, ...res.data }); } // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject(false); }, ); return instance; };
{ // eslint-disable-next-line no-param-reassign,no-underscore-dangle err.config.__isRetryRequest = true; return axios(err.config); }
conditional_block
ln-CG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. *
// THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === Math.floor(n) && n >= 0 && n <= 1) return 1; return 5; } export default [ 'ln-CG', [['ntɔ́ngɔ́', 'mpókwa'], u, u], u, [ ['e', 'y', 'm', 'm', 'm...
* Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */
random_line_split
ln-CG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
(n: number): number { if (n === Math.floor(n) && n >= 0 && n <= 1) return 1; return 5; } export default [ 'ln-CG', [['ntɔ́ngɔ́', 'mpókwa'], u, u], u, [ ['e', 'y', 'm', 'm', 'm', 'm', 'p'], ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], [ 'eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', ...
plural
identifier_name
ln-CG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'ln-CG', [['ntɔ́ngɔ́', 'mpókwa'], u, u], u, [ ['e', 'y', 'm', 'm', 'm', 'm', 'p'], ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'], [ 'eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mokɔlɔ mwa mísáto', 'mokɔlɔ ya mínéi', 'mokɔlɔ ya mítáno', 'mpɔ́sɔ' ], ['eye'...
{ if (n === Math.floor(n) && n >= 0 && n <= 1) return 1; return 5; }
identifier_body
util.py
#!/usr/bin/env python # Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import heapq import os import platform import random import signal import subprocess # Base dir of the build products for Release an...
original_data = [rec for (_, _, rec) in self.data] return sorted(original_data, key=self.key, reverse=True)
identifier_body
util.py
#!/usr/bin/env python # Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import heapq import os import platform import random import signal import subprocess # Base dir of the build products for Release an...
(): """Kill stray processes on the system that started in the same out directory. All swarming tasks share the same out directory location. """ if platform.system() != 'Linux': return for pid, cmd in list_processes_linux(): try: print('Attempting to kill %d - %s' % (pid, cmd)) os.kill(pid...
kill_processes_linux
identifier_name
util.py
#!/usr/bin/env python # Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import heapq import os import platform import random import signal import subprocess # Base dir of the build products for Release an...
def extra_key(self): # Avoid key clash in tuples sent to the heap. # We want to avoid comparisons on the last element of the tuple # since those elements might not be comparable. self.discriminator += 1 return self.discriminator def as_list(self): original_data = [rec for (_, _, rec) in s...
heapq.heappop(self.data)
conditional_block
util.py
#!/usr/bin/env python # Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import heapq import os import platform import random import signal import subprocess # Base dir of the build products for Release an...
If you need a reversed behaviour (collect min values) just provide an inverse key.""" def __init__(self, size, key=None): self.size = size self.key = key or (lambda x: x) self.data = [] self.discriminator = 0 def add(self, elem): elem_k = self.key(elem) heapq.heappush(self.data, (elem_...
"""Utility collection for gathering a fixed number of elements with the biggest value for the given key. It employs a heap from which we pop the smallest element when the collection is 'full'.
random_line_split
melinda-preprocess.spec.js
/** * * @licstart The following is the entire license notice for the JavaScript code in this file. * * Melinda-related modules for recordLoader * * Copyright (c) 2015-2017 University Of Helsinki (The National Library Of Finland) * * This file is part of record-loader-melinda * * record-loader-melinda is fre...
function createProcessor() { return processorFactory({ validators: [{ name: 'sort-tag', options: '500' }] }).setLogger({ info: function() {}, debug: function() {} }); } describe('factory', function() ...
describe('processors', function() { describe('hostcomp-preprocess', function() {
random_line_split
melinda-preprocess.spec.js
/** * * @licstart The following is the entire license notice for the JavaScript code in this file. * * Melinda-related modules for recordLoader * * Copyright (c) 2015-2017 University Of Helsinki (The National Library Of Finland) * * This file is part of record-loader-melinda * * record-loader-melinda is fre...
(chai, chaiAsPromised, MarcRecord, Promise, processorFactory) { 'use strict'; var expect = chai.expect; chai.use(chaiAsPromised); describe('processors', function() { describe('hostcomp-preprocess', function() { function createProcessor() { return processorFactory({ ...
factory
identifier_name
melinda-preprocess.spec.js
/** * * @licstart The following is the entire license notice for the JavaScript code in this file. * * Melinda-related modules for recordLoader * * Copyright (c) 2015-2017 University Of Helsinki (The National Library Of Finland) * * This file is part of record-loader-melinda * * record-loader-melinda is fre...
{ 'use strict'; var expect = chai.expect; chai.use(chaiAsPromised); describe('processors', function() { describe('hostcomp-preprocess', function() { function createProcessor() { return processorFactory({ validators: [{ name: 'sort-tag', ...
identifier_body
melinda-preprocess.spec.js
/** * * @licstart The following is the entire license notice for the JavaScript code in this file. * * Melinda-related modules for recordLoader * * Copyright (c) 2015-2017 University Of Helsinki (The National Library Of Finland) * * This file is part of record-loader-melinda * * record-loader-melinda is fre...
}(this, factory)); function factory(chai, chaiAsPromised, MarcRecord, Promise, processorFactory) { 'use strict'; var expect = chai.expect; chai.use(chaiAsPromised); describe('processors', function() { describe('hostcomp-preprocess', function() { function createProcessor() ...
{ module.exports = factory( require('chai'), require('chai-as-promised'), require('marc-record-js'), require('@natlibfi/es6-polyfills/lib/polyfills/promise'), require('../../lib/hostcomp/processors/preprocess/melinda') ); }
conditional_block
mouth.ts
export const mouth: ComponentGroup = { default: (components: ComponentPickCollection, colors: ColorPickCollection) => `<path d="M27.93 46a1 1 0 0 1 1-1h9.14a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-1.14a5 5 0 0 1-5-5Z" fill="#66253C"/><path d="M35.76 50.7a5 5 0 0 1-1.69.3h-1.14a5 5 0 0 1-5-4.8c.77-.29 1.9-.25 3.02-.22L32 46...
import type { ComponentGroup, ComponentPickCollection, ColorPickCollection, } from '../static-types';
random_line_split
vbp-optim.py
from vsvbp import container, solver import argparse, sys, os, re def parse(inputfile): """ Parse a file using format from Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)] Format: d (number of dimensions) C_1 ... C_d ca...
return natural_sort(dirs) def get_files(directory): files = [os.path.join(directory,name) for name in os.listdir(directory) if os.path.isfile(os.path.join(directory, name))] files.sort() return natural_sort(files) def optim_dir(directory, level=0): files = get_files(directory) fo...
if os.path.isdir(os.path.join(directory, name))]
random_line_split
vbp-optim.py
from vsvbp import container, solver import argparse, sys, os, re def parse(inputfile): """ Parse a file using format from Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)] Format: d (number of dimensions) C_1 ... C_d ca...
def optim_rec(directory, level=0): subdir = get_subdirectories(directory) print " "*level+ "|"+"- "+directory.split('/').pop() if not subdir: return optim_dir(directory, level+1) for d in subdir: optim_rec(d, level+1) def optimize(filename, level=0): fl = open(filename) ...
optimize(f, level)
conditional_block
vbp-optim.py
from vsvbp import container, solver import argparse, sys, os, re def parse(inputfile): """ Parse a file using format from Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)] Format: d (number of dimensions) C_1 ... C_d ca...
def optimize(filename, level=0): fl = open(filename) items, tbin = parse(fl) if not items: fl.close() return opt = len(solver.optimize(items, tbin, optimize.dp, optimize.seed).bins) template = "{0:50}{1:10}" if level == 0: st = filename.split('/').pop() print...
subdir = get_subdirectories(directory) print " "*level+ "|"+"- "+directory.split('/').pop() if not subdir: return optim_dir(directory, level+1) for d in subdir: optim_rec(d, level+1)
identifier_body
vbp-optim.py
from vsvbp import container, solver import argparse, sys, os, re def parse(inputfile): """ Parse a file using format from Brandao et al. [Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression (2013)] Format: d (number of dimensions) C_1 ... C_d ca...
(directory): files = [os.path.join(directory,name) for name in os.listdir(directory) if os.path.isfile(os.path.join(directory, name))] files.sort() return natural_sort(files) def optim_dir(directory, level=0): files = get_files(directory) for f in files: optimize(f, level) de...
get_files
identifier_name
0.0.javascript_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // tslint:disable:no-any import { schema } from '@angular-devkit/core'; const { serializers } = schema; export fun...
(registry: schema.JsonSchemaRegistry, schema: any) { const value = { 'firstName': 'Hans', 'lastName': 'Larsen', 'age': 30, }; registry.addSchema('', schema); const v = (new serializers.JavascriptSerializer()).serialize('', registry)(value); expect(v.firstName).toBe('Hans'); expect(v.lastName)...
works
identifier_name
0.0.javascript_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // tslint:disable:no-any import { schema } from '@angular-devkit/core'; const { serializers } = schema; export fun...
// This should throw as the value is required. expect(() => v.firstName = undefined).toThrow(); }
expect(() => v.age = undefined).not.toThrow(); expect(() => v.firstName = 0).toThrow(); expect(() => v.firstName = []).toThrow();
random_line_split
0.0.javascript_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // tslint:disable:no-any import { schema } from '@angular-devkit/core'; const { serializers } = schema; export fun...
{ const value = { 'firstName': 'Hans', 'lastName': 'Larsen', 'age': 30, }; registry.addSchema('', schema); const v = (new serializers.JavascriptSerializer()).serialize('', registry)(value); expect(v.firstName).toBe('Hans'); expect(v.lastName).toBe('Larsen'); expect(v.age).toBe(30); v.age...
identifier_body
DialogRenderer.js
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2020 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', './BarRenderer'], function (jQuery, BarRenderer) { "use strict"; /** * Dialog renderer. ...
if (oControl._forceDisableScrolling) { oRm.addClass("sapMDialogWithScrollCont"); } if (oSubHeader && oSubHeader.getVisible()) { oRm.addClass("sapMDialogWithSubHeader"); } if (bMessage) { oRm.addClass("sapMMessageDialog"); } if (!bVerticalScrolling) { oRm.addClass("sapMDialogVer...
{ oRm.writeAccessibilityState(oControl, { role: "dialog" }); }
conditional_block
DialogRenderer.js
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2020 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', './BarRenderer'], function (jQuery, BarRenderer) { "use strict"; /** * Dialog renderer. ...
oRm.addClass("sapMDialogPhone"); } if (bDraggable && !bStretch) { oRm.addClass("sapMDialogDraggable"); } // test dialog with sap-ui-xx-formfactor=compact if (sap.m._bSizeCompact) { oRm.addClass("sapUiSizeCompact"); } oRm.writeClasses(); var sTooltip = oControl.getTooltip_AsString...
random_line_split
sinewave.py
""" sinewave ======== Generates a sinusoidal wave of programmable period. 32 points are generated per cycle. Arguments:: { "period" : the period of the cycle e.g. "PT10M" (the above can be an array, in which case multiple sinewaves are generated and added. This can be useful for Fourier synthesis,...
(self, engine, device, params): self.engine = engine self.device = device p = params.get("period", "P1D") # We accept a string or a list of strings self.periods = [] # But internally always operate on a list if type(p) == list: for i in p: self.per...
__init__
identifier_name
sinewave.py
""" sinewave ======== Generates a sinusoidal wave of programmable period. 32 points are generated per cycle. Arguments:: { "period" : the period of the cycle e.g. "PT10M" (the above can be an array, in which case multiple sinewaves are generated and added. This can be useful for Fourier synthesis,...
t2 = min(t2) t2 += self.initTime return t2 def period(self): return float(self.period) / POINTS_PER_CYCLE class dummy_engine(): def get_now(self): return 0 if __name__ == "__main__": if False: print("Sinewave") s = Sinewave(dummy_engine(), Non...
random_line_split
sinewave.py
""" sinewave ======== Generates a sinusoidal wave of programmable period. 32 points are generated per cycle. Arguments:: { "period" : the period of the cycle e.g. "PT10M" (the above can be an array, in which case multiple sinewaves are generated and added. This can be useful for Fourier synthesis,...
def next_change(self, t=None): """Return a future time when the next event will happen""" if t is None: t = self.engine.get_now() t -= self.initTime if self.sample_period is not None: t2 = t + self.sample_period else: t2 = [] # Find ...
"""Return a sinewave.""" if t is None: t = self.engine.get_now() if (not t_relative): t -= self.initTime t = self.randomise_phase(t) v = 0 for p,a in zip(self.periods, self.amplitudes): v = v + math.sin((2 * math.pi * t) / float(p)) * a/2.0 + ...
identifier_body
sinewave.py
""" sinewave ======== Generates a sinusoidal wave of programmable period. 32 points are generated per cycle. Arguments:: { "period" : the period of the cycle e.g. "PT10M" (the above can be an array, in which case multiple sinewaves are generated and added. This can be useful for Fourier synthesis,...
self.randomise_phase_by = params.get("randomise_phase_by", None) self.precision = params.get("precision", None) self.initTime = engine.get_now() def randomise_phase(self, t): if self.randomise_phase_by is None: return t return hash(self.device.get_property(self....
self.sample_period = float(isodate.parse_duration(self.sample_period).total_seconds())
conditional_block
requests.js
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
/** * Inherits from BaseRequest. */ util.inherits(BatchRequest, BaseRequest); /** * Adds a request to the batch request. * @param {Request} request A Request object to add to the batch. * * @return {BatchRequest} Returns itself. */ BatchRequest.prototype.add = function(request) { this.requests_.push(request...
{ BatchRequest.super_.call(this); this.requests_ = []; }
identifier_body
requests.js
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
() { BatchRequest.super_.call(this); this.requests_ = []; } /** * Inherits from BaseRequest. */ util.inherits(BatchRequest, BaseRequest); /** * Adds a request to the batch request. * @param {Request} request A Request object to add to the batch. * * @return {BatchRequest} Returns itself. */ BatchRequest.pr...
BatchRequest
identifier_name
requests.js
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
queryParams = queryParams || {}; if (this.apiKey) { queryParams.key = this.apiKey; } return buildUri(this.apiMeta.rootUrl, p, queryParams); }; /** * Generates path to the method with given params. * @param {object} queryParams Query params. * @return {String} The method's REST path. */ Request.pro...
{ p.unshift('/upload'); }
conditional_block
requests.js
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
* @param {object} apiMeta Schema returned by Discovery API. * @param {string} methodMeta Method metadata. * @param {?object} opt_params Required Parameters. If none are required, * expected to be not passed. * @param {object=} opt_body Optional body. * @param {object=} opt_defaultPar...
random_line_split
var-captured-in-nested-closure.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ a: int, b: f64, c: uint } fn main() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = box 6; let managed = @7; let closure = || { let closure_local = 8; ...
Struct
identifier_name
var-captured-in-nested-closure.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn zzz() {()}
{ let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = box 6; let managed = @7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); ...
identifier_body
var-captured-in-nested-closure.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print variable // gdb-check:$1 = 1 // gdb-command:print constant // gdb-check:$2 = 2 // gdb-command:print a_struct // gdb-check:$3 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$4 = {a = -3, b = 4.5, c = 5} // ...
// compile-flags:-g
random_line_split
index.js
// *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-g...
}
{ on(`before:browser:launch`, (browser = {}, args) => { if ( browser.name === `chrome` && process.env.CYPRESS_CONNECTION_TYPE === `slow` ) { args.push(`--force-effective-connection-type=2G`) } return args }) }
conditional_block
index.js
// *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-g...
module.exports = (on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config if (process.env.CYPRESS_CONNECTION_TYPE) { on(`before:browser:launch`, (browser = {}, args) => { if ( browser.name === `chrome` && process.env.CYPRESS_...
// This function is called when a project is opened or re-opened (e.g. due to // the project's config changing)
random_line_split
str.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 std::alloc::{OncePool}; #[test] fn debug_char() { let mut buf = [0; 30]; let mut buf = Vec::with_pool(On...
display_str() { let mut buf = [0; 30]; let mut buf = Vec::with_pool(OncePool::new(buf.as_mut())); write!(&mut buf, "{}", "aä日"); test!(&*buf == "aä日"); }
mut buf = [0; 30]; let mut buf = Vec::with_pool(OncePool::new(buf.as_mut())); write!(&mut buf, "{:?}", "aä日"); test!(&*buf == "\"a\\u{e4}\\u{65e5}\""); } #[test] fn
identifier_body
str.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 std::alloc::{OncePool}; #[test] fn debug_char() { let mut buf = [0; 30]; let mut buf = Vec::with_pool(On...
mut buf = [0; 30]; let mut buf = Vec::with_pool(OncePool::new(buf.as_mut())); write!(&mut buf, "{}", "aä日"); test!(&*buf == "aä日"); }
) { let
identifier_name