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
test_addonconf.py
import sys import unittest sys.path.insert(0, "../src/build") import addonconf class AddonConfModuleTestCase(unittest.TestCase): def test_load(self): # act config = addonconf.load("configs/config.json")
config = addonconf.load("configs/config.json.1") # assert self.assertEqual(config, None, "Wrong return value for unvalide config") def test_load3(self): # arrange correct_config = {'version': '0.1', 'xpi': {'theme': 'firefox-theme-test.xpi', 'package': 'firefox-test-@VERSIO...
# assert self.assertEqual(config, None, "Wrong return value for not exists config") def test_load2(self): # act
random_line_split
test_addonconf.py
import sys import unittest sys.path.insert(0, "../src/build") import addonconf class AddonConfModuleTestCase(unittest.TestCase): def test_load(self): # act config = addonconf.load("configs/config.json") # assert self.assertEqual(config, None, "Wrong return value for not exists con...
unittest.main()
conditional_block
htmlformelement.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::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::d...
(&self) -> DOMString { ~"" } pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult { Ok(()) } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_doc().document().window; HTMLCollection::new(window, ~[]) } p...
Target
identifier_name
htmlformelement.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::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::d...
pub fn SetMethod(&mut self, _method: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn NoValidate(&self) -> bool { false } pub fn SetNoValidate(...
}
random_line_split
htmlformelement.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::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::d...
pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult { Ok(()) } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_doc().document().window; HTMLCollection::new(window, ~[]) } pub fn Length(&self) -> i32 { 0 ...
{ ~"" }
identifier_body
feature_selection.py
from collections import Counter def TFIDF(TF, complaints, term): if TF >= 1: n = len(complaints) x = sum([1 for complaint in complaints if term in complaint['body']]) return log(TF + 1) * log(n / x) else: return 0 def DF(vocab, complaints): term_DF = dict() for term in ...
features = [] chi_table = dict() N = len(complaints) for term in vocab: chi_table[term] = dict() for category in categories: chi_table[term][category] = dict() A = 0 B = 0 C = 0 D = 0 for complaint in complaints: ...
identifier_body
feature_selection.py
from collections import Counter def TFIDF(TF, complaints, term): if TF >= 1: n = len(complaints) x = sum([1 for complaint in complaints if term in complaint['body']]) return log(TF + 1) * log(n / x) else: return 0 def DF(vocab, complaints): term_DF = dict() for term in ...
B += 1 if term not in complaint['body'] and complaint['category'] == category: C += 1 if term not in complaint['body'] and complaint['category'] != category: D += 1 try: chi_table[term][category]['chi...
if term in complaint['body'] and complaint['category'] == category: A += 1 if term in complaint['body'] and complaint['category'] != category:
random_line_split
feature_selection.py
from collections import Counter def TFIDF(TF, complaints, term): if TF >= 1: n = len(complaints) x = sum([1 for complaint in complaints if term in complaint['body']]) return log(TF + 1) * log(n / x) else: return 0 def
(vocab, complaints): term_DF = dict() for term in vocab: term_DF[term] = sum([1 for complaint in complaints if term in complaint['body']]) threshold = 3 features = [term for term in term_DF.keys() if term_DF[term] > threshold] return features def chi_square(vocab, complaints, categories):...
DF
identifier_name
feature_selection.py
from collections import Counter def TFIDF(TF, complaints, term): if TF >= 1: n = len(complaints) x = sum([1 for complaint in complaints if term in complaint['body']]) return log(TF + 1) * log(n / x) else: return 0 def DF(vocab, complaints): term_DF = dict() for term in ...
chi_table[term]['chi_average'] = float() for category in categories: P = chi_table[term][category]['freq'] / N chi_table[term]['chi_average'] += P * chi_table[term][category]['chi'] if chi_table[term]['chi_average'] > 3: features.append(term) print('Extr...
chi_table[term][category] = dict() A = 0 B = 0 C = 0 D = 0 for complaint in complaints: if term in complaint['body'] and complaint['category'] == category: A += 1 if term in complaint['body'] and complaint['c...
conditional_block
__init__.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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 ...
# The code below enables nosetests to work with i18n _() blocks import __builtin__ setattr(__builtin__, '_', lambda x: x)
random_line_split
dataStorageSvc.js
MEMO.services.dataStorageSvc = (function () { "use strict"; (function () { // immediate ivoke functions come here. })(); var _add = function (key, obj) { var value = JSON.stringify(obj); localStorage.setItem(key, value); }; var _get = function (key) { return JS...
} }; return { save: _add, add: _add, addUpdate: _add, get: _get, remove: _remove, changeOpt: _changeOption }; })();
a[key] = b[key]; };
conditional_block
dataStorageSvc.js
MEMO.services.dataStorageSvc = (function () { "use strict"; (function () { // immediate ivoke functions come here. })(); var _add = function (key, obj) { var value = JSON.stringify(obj); localStorage.setItem(key, value); }; var _get = function (key) { return JS...
return { save: _add, add: _add, addUpdate: _add, get: _get, remove: _remove, changeOpt: _changeOption }; })();
};
random_line_split
core.server.controller.test.js
/** * Created by Brennon Bortz on 8/6/14. */ 'use strict'; // Server var server = require('../../../server'); var app; // Config module var config = require('../../../config/config'); // Testing tools var request = require('supertest'); var should = require('chai').should(); describe('Core Controller Tests', fun...
cookieB = res.header['set-cookie']; cookieA.should.not.equal(cookieB); done(); }); }); }); });
{ return done(err); }
conditional_block
core.server.controller.test.js
/** * Created by Brennon Bortz on 8/6/14. */ 'use strict'; // Server var server = require('../../../server'); var app; // Config module var config = require('../../../config/config'); // Testing tools var request = require('supertest'); var should = require('chai').should(); describe('Core Controller Tests', fun...
var agent = request.agent('localhost:' + config.port); var cookieA, cookieB; it('should be in use', function(done) { agent .get('/') .expect('set-cookie', /connect\.sid.*/) .end(function(err, res) { if (err) { ...
random_line_split
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcV...
} pub fn now_ms() -> i64 { let ts = time::now_utc().to_timespec(); ts.sec * 1000 + ts.nsec as i64 / 1000000 } pub fn mkdir_existing(path: &Path) -> io::Result<()> { fs::create_dir(path) .or_else(|err| if err.kind() == io::ErrorKind::AlreadyExists { Ok(()) } else { ...
{ match self { Ok(_) => (), Err(_) => (), } }
identifier_body
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcV...
} pub mod version { include!(concat!(env!("OUT_DIR"), "/version.rs")); pub fn version_string() -> String { format!("librespot-{}", short_sha()) } } pub fn hexdump(data: &[u8]) { for b in data.iter() { eprint!("{:02X} ", b); } eprintln!(""); } pub trait IgnoreExt { fn igno...
return vec
random_line_split
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcV...
<'a>(&'a self, size: usize) -> StrChunks<'a> { StrChunks(self, size) } } impl <'s> Iterator for StrChunks<'s> { type Item = &'s str; fn next(&mut self) -> Option<&'s str> { let &mut StrChunks(data, size) = self; if data.is_empty() { None } else { let ...
chunks
identifier_name
trades.js
import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import contract from 'truffle-contract'; import ExchangeJson from '@melonproject/protocol/build/contracts/Exchange.json'; import web3 from '/imports/lib/web3'; import addressList from '/imports/melon/interface/addressList'; import specs fro...
// COLLECTION METHODS Trades.watch = () => { // only the server should update the database! if (Meteor.isClient) return; const Exchange = contract(ExchangeJson); Exchange.setProvider(web3.currentProvider); const exchangeContract = Exchange.at(addressList.exchange); const trades = exchangeContract.Trade(...
), ); }
random_line_split
calendar-body.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 */ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angu...
{ /* The label for the table. (e.g. "Jan 2017"). */ @Input() label: string; /* The cells to display in the table. */ @Input() rows: MdCalendarCell[][]; /* The value in the table that corresponds to today. */ @Input() todayValue: number; /* The value in the table that is currently selected. */ @Input...
MdCalendarBody
identifier_name
calendar-body.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 */ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angu...
* @docs-private */ export class MdCalendarCell { constructor(public value: number, public displayValue: string, public ariaLabel: string, public enabled: boolean) {} } /* * An internal component used to display calendar data in a table. * @docs-private */ @Component({ ...
/* * An internal class that represents the data corresponding to a single calendar cell.
random_line_split
calendar-body.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 */ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angu...
return cellNumber == this.activeCell; } }
{ cellNumber -= this._firstRowOffset; }
conditional_block
calendar-body.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 */ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angu...
_isActiveCell(rowIndex: number, colIndex: number): boolean { let cellNumber = rowIndex * this.numCols + colIndex; // Account for the fact that the first row may not have as many cells. if (rowIndex) { cellNumber -= this._firstRowOffset; } return cellNumber == this.activeCell; } }
{ return this.rows && this.rows.length && this.rows[0].length ? this.numCols - this.rows[0].length : 0; }
identifier_body
subnet.py
# Copyright 2014 Isotoma Limited # # 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...
class Describe(SimpleDescribe, Plan): resource = Subnet service_name = "ec2" api_version = "2015-10-01" describe_action = "describe_subnets" describe_envelope = "Subnets" key = "SubnetId" signature = (Present("name"), Present("vpc"), Present("cidr_block")) def get_describe_filters(...
if cidr_block not in self.vpc.cidr_block: raise errors.InvalidParameter( "{} not inside network {}".format(self.cidr_block, self.vpc.cidr_block) ) return cidr_block
identifier_body
subnet.py
# Copyright 2014 Isotoma Limited # # 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...
naa_changed = False if not self.resource.network_acl: return if not self.object: naa_changed = True elif not self.object.get("NetworkAclAssociationId", None): naa_changed = True elif self.runner.get_plan( self.resource.network_acl...
yield self.generic_action( "Disassociate route table", self.client.disassociate_route_table, AssociationId=self.object["RouteTableAssociationId"], )
conditional_block
subnet.py
# Copyright 2014 Isotoma Limited # # 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...
class Destroy(SimpleDestroy, Describe): destroy_action = "delete_subnet"
)
random_line_split
subnet.py
# Copyright 2014 Isotoma Limited # # 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...
(SimpleDescribe, Plan): resource = Subnet service_name = "ec2" api_version = "2015-10-01" describe_action = "describe_subnets" describe_envelope = "Subnets" key = "SubnetId" signature = (Present("name"), Present("vpc"), Present("cidr_block")) def get_describe_filters(self): vp...
Describe
identifier_name
index.d.ts
// Type definitions for @loadable/component 5.13 // Project: https://github.com/smooth-code/loadable-components // Definitions by: Martynas Kadiša <https://github.com/martynaskadisa> // Daniel Playfair Cal <https://github.com/hedgepigdaniel> // Definitions: https://github.com/DefinitelyTyped/DefinitelyT...
options?: Options<React.ComponentProps<Component>, Component>, ): LoadableClassComponent<Component>; declare const loadable: typeof loadableFunc & { lib: typeof lib }; export default loadable; export namespace lazy { function lib<Module>(loadFn: (props: object) => Promise<Module>): LoadableLibrary<Module>; }...
declare function loadableFunc<Component extends React.ComponentClass<any>>( loadFn: (props: React.ComponentProps<Component>) => Promise<Component | { default: Component }>,
random_line_split
findNoteCounts.py
# Import the Evernote client from evernote.api.client import EvernoteClient # Import the Evernote note storetypes to get note datatypes # to properly get note/tag counts (note filter) import evernote.edam.notestore.ttypes as NoteStoreTypes # Define access token either: # Developer Tokens (https://dev.evernote.com/do...
if not note_counts.tagCounts and not note_counts.notebookCounts: print "No results"
print "Found results from %s tags" % len(note_counts.notebookCounts) for tag in note_counts.tagCounts: print " Tag with GUID %s has %s note(s) that match the filter" % (tag, note_counts.tagCounts[tag])
conditional_block
findNoteCounts.py
# Import the Evernote client from evernote.api.client import EvernoteClient # Import the Evernote note storetypes to get note datatypes # to properly get note/tag counts (note filter) import evernote.edam.notestore.ttypes as NoteStoreTypes # Define access token either: # Developer Tokens (https://dev.evernote.com/do...
#note_filter.includeAllReadableNotebooks=True # (Boolean) Include note/tags that are in the trash in your note counts include_trash = True # Returns an object which maps the number of notes captured by the filter to the corresponding # notebook GUID note_counts = note_store.findNoteCounts( note_filter, include_trash ...
# Uncomment the following line to set note filter includeAllReadableNotebooks attribute # to include all readable business notebooks in a search # search must be performed on a business note store with a business auth token
random_line_split
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use a...
(out: *mut FILE, s: &str) { for c in s.chars() { putc(c as i32, out); usleep(20); } } fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expe...
charatatime
identifier_name
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use a...
putc(c as i32, out); usleep(20); } } fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expect("fork error"); match pid { 0 =...
random_line_split
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use a...
fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expect("fork error"); match pid { 0 => charatatime(stdout, "output from child \n"), ...
{ for c in s.chars() { putc(c as i32, out); usleep(20); } }
identifier_body
volume.py
import numpy as np from scipy import sparse from . import Mapper from . import samplers class VolumeMapper(Mapper): @classmethod def _cache(cls, filename, subject, xfmname, **kwargs): from .. import db masks = [] xfm = db.get_xfm(subject, xfmname, xfmtype='coord') pia = db.get_...
return mask class ConvexPolyhedra(VolumeMapper): @classmethod def _getmask(cls, pia, wm, polys, shape, npts=1024): from .. import mp from .. import polyutils rand = np.random.rand(npts, 3) csrshape = len(wm), np.prod(shape) def func(pts): if len(pt...
poly = tvtk.PolyData(points=pts, polys=faces) measure.set_input(poly) measure.update() totalvol = measure.volume ccs.set_input(poly) measure.set_input(ccs.output) bmin = pts.min(0).round().astype(int) bmax =...
conditional_block
volume.py
import numpy as np from scipy import sparse from . import Mapper from . import samplers class VolumeMapper(Mapper): @classmethod def _cache(cls, filename, subject, xfmname, **kwargs): from .. import db masks = [] xfm = db.get_xfm(subject, xfmname, xfmtype='coord') pia = db.get_...
(cls, pia, wm, polys, shape, npts=1024): from .. import mp from .. import polyutils rand = np.random.rand(npts, 3) csrshape = len(wm), np.prod(shape) def func(pts): if len(pts) > 0: #generate points within the bounding box samples = ra...
_getmask
identifier_name
volume.py
from . import samplers class VolumeMapper(Mapper): @classmethod def _cache(cls, filename, subject, xfmname, **kwargs): from .. import db masks = [] xfm = db.get_xfm(subject, xfmname, xfmtype='coord') pia = db.get_surf(subject, "pia", merge=False, nudge=False) wm = db.get...
import numpy as np from scipy import sparse from . import Mapper
random_line_split
volume.py
import numpy as np from scipy import sparse from . import Mapper from . import samplers class VolumeMapper(Mapper): @classmethod def _cache(cls, filename, subject, xfmname, **kwargs): from .. import db masks = [] xfm = db.get_xfm(subject, xfmname, xfmtype='coord') pia = db.get_...
class ConvexLanczos(VolumeMapper): def _sample(self, pts): raise NotImplementedError
@staticmethod def _sample(pts, shape, norm): (x, y, z), floor = np.modf(pts.T) floor = floor.astype(int) ceil = floor + 1 x[x < 0] = 0 y[y < 0] = 0 z[z < 0] = 0 i000 = np.ravel_multi_index((floor[2], floor[1], floor[0]), shape, mode='clip') i100 = np....
identifier_body
test_template_format.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test...
expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str))
random_line_split
test_template_format.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_fo...
break
conditional_block
test_template_format.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'})
identifier_body
test_template_format.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', fi...
JsonYamlResolvedCompareTest
identifier_name
config.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
(): """ Retrieve the deployment_config_file config item, formatted as an absolute pathname. """ config_path = cfg.CONF.find_file( cfg.CONF.paste_deploy['api_paste_config']) if config_path is None: return None return os.path.abspath(config_path) def load_paste_app(app_name=...
_get_deployment_config_file
identifier_name
config.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
else: domain_admin_user = cfg.CONF.stack_domain_admin domain_admin_password = cfg.CONF.stack_domain_admin_password if not (domain_admin_user and domain_admin_password): raise exception.Error(_('heat.conf misconfigured, cannot ' 'specify "stack...
LOG.warn(_LW('stack_user_domain_id or stack_user_domain_name not ' 'set in heat.conf falling back to using default'))
conditional_block
config.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
def load_paste_app(app_name=None): """ Builds and returns a WSGI app from a paste config file. We assume the last config file specified in the supplied ConfigOpts object is the paste config file. :param app_name: name of the application to load :raises RuntimeError when config file cannot ...
""" Retrieve the deployment_config_file config item, formatted as an absolute pathname. """ config_path = cfg.CONF.find_file( cfg.CONF.paste_deploy['api_paste_config']) if config_path is None: return None return os.path.abspath(config_path)
identifier_body
config.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
yield client_specific_group, clients_opts yield 'clients_heat', heat_client_opts yield 'clients_nova', client_http_log_debug_opts yield 'clients_cinder', client_http_log_debug_opts cfg.CONF.register_group(paste_deploy_group) cfg.CONF.register_group(auth_password_group) cfg.CONF.register_group(rev...
random_line_split
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE ...
}
{ panic!("discarding memory with mprotect() failed"); }
conditional_block
arena.rs
use std::ptr;
pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) a...
use crate::gc::Address; use crate::mem; use crate::os::page_size;
random_line_split
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE ...
(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res != 0 { panic!("discarding memory with madvise() failed"); } let res = unsafe { libc::m...
discard
identifier_name
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE ...
pub fn discard(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res != 0 { panic!("discarding memory with madvise() failed"); } let res = ...
{ debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ...
identifier_body
mod.rs
// Copyright 2017 Kai Strempel
// // 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 // distribut...
random_line_split
mod.rs
// Copyright 2017 Kai Strempel // // 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...
() { use Client; use volumes::VolumesClient; let client = Client::from_env(); let volumes_client = VolumesClient::new(&client); let volumes = volumes_client.get(); assert!(volumes.is_ok()); } }
it_works
identifier_name
mod.rs
// Copyright 2017 Kai Strempel // // 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...
} #[cfg(test)] mod tests { #[test] fn it_works() { use Client; use volumes::VolumesClient; let client = Client::from_env(); let volumes_client = VolumesClient::new(&client); let volumes = volumes_client.get(); assert!(volumes.is_ok()); } }
{ get(self.client, "volumes") }
identifier_body
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2011 OpenStack Foundation # (c) Cop...
else: return "tap" else: LOG.info(_LI("tap-ctl check: %s"), out) except OSError as exc: if exc.errno == errno.ENOENT: LOG.debug("tap-ctl tool is not installed") else: ...
return "tap2"
conditional_block
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2011 OpenStack Foundation # (c) Cop...
def update_mtime(path): """Touch a file without being the owner. :param path: File bump the mtime on """ try: execute('touch', '-c', path, run_as_root=True) except processutils.ProcessExecutionError as exc: # touch can intermittently fail when launching several instances with ...
"""Change ownership of file or directory :param path: File or directory whose ownership to change :param owner: Desired new owner (given as uid or username) """ execute('chown', owner, path, run_as_root=True)
identifier_body
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2011 OpenStack Foundation # (c) Cop...
(path, basename=True, format=None): """Get the backing file of a disk image :param path: Path to the disk image :returns: a path to the image's backing store """ backing_file = images.qemu_img_info(path, format).backing_file if backing_file and basename: backing_file = os.path.basename(...
get_disk_backing_file
identifier_name
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2011 OpenStack Foundation # (c) Cop...
This function does not attempt raw conversion, as these images will already be in raw format. """ images.fetch(context, image_id, target) def get_instance_path(instance, relative=False): """Determine the correct path for instance storage. This method determines the directory name for instance...
def fetch_raw_image(context, target, image_id): """Grab initrd or kernel image.
random_line_split
stata.py
""" pygments.lexers.stata ~~~~~~~~~~~~~~~~~~~~~ Lexer for Stata :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, default, include, words from pygments.token import Comment, Keyword, Name...
(RegexLexer): """ For `Stata <http://www.stata.com/>`_ do files. .. versionadded:: 2.2 """ # Syntax based on # - http://fmwww.bc.edu/RePEc/bocode/s/synlightlist.ado # - https://github.com/isagalaev/highlight.js/blob/master/src/languages/stata.js # - https://github.com/jpitblado/vim-stat...
StataLexer
identifier_name
stata.py
""" pygments.lexers.stata ~~~~~~~~~~~~~~~~~~~~~ Lexer for Stata :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, default, include, words from pygments.token import Comment, Keyword, Name...
(r'\$(\{|(?=[$`]))', Name.Variable.Global, 'macro-global-nested', '#pop'), (r'\$', Name.Variable.Global, 'macro-global-name', '#pop'), (r'`', Name.Variable, 'macro-local', '#pop'), (r'\w{1,32}', Name.Variable.Global, '#pop'), ], # Built in functions and st...
(r'\w', Name.Variable.Global), # fallback default('#pop'), ], 'macro-global-name': [
random_line_split
stata.py
""" pygments.lexers.stata ~~~~~~~~~~~~~~~~~~~~~ Lexer for Stata :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, default, include, words from pygments.token import Comment, Keyword, Name...
""" For `Stata <http://www.stata.com/>`_ do files. .. versionadded:: 2.2 """ # Syntax based on # - http://fmwww.bc.edu/RePEc/bocode/s/synlightlist.ado # - https://github.com/isagalaev/highlight.js/blob/master/src/languages/stata.js # - https://github.com/jpitblado/vim-stata/blob/master/synt...
identifier_body
MathML.js
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/vi/MathML.js * * Copyright (c) 2009-2015 The MathJax Consortium * * Licensed under the Apache License, Version 2.0...
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("vi","MathML",{ version: "2.5.0", isLoaded: true, strings: { ...
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
stata.py
import pandas as pd from larray.core.array import Array from larray.inout.pandas import from_frame __all__ = ['read_stata'] def read_stata(filepath_or_buffer, index_col=None, sort_rows=False, sort_columns=False, **kwargs) -> Array: r""" Reads Stata .dta file and returns an Array with the contents Param...
Defaults to False. Returns ------- Array See Also -------- Array.to_stata Notes ----- The round trip to Stata (Array.to_stata followed by read_stata) loose the name of the "column" axis. Examples -------- >>> read_stata('test.dta') # doctest:...
Whether or not to sort the rows alphabetically (sorting is more efficient than not sorting). This only makes sense in combination with index_col. Defaults to False. sort_columns : bool, optional Whether or not to sort the columns alphabetically (sorting is more efficient than not sorting).
random_line_split
stata.py
import pandas as pd from larray.core.array import Array from larray.inout.pandas import from_frame __all__ = ['read_stata'] def read_stata(filepath_or_buffer, index_col=None, sort_rows=False, sort_columns=False, **kwargs) -> Array:
r""" Reads Stata .dta file and returns an Array with the contents Parameters ---------- filepath_or_buffer : str or file-like object Path to .dta file or a file handle. index_col : str or None, optional Name of column to set as index. Defaults to None. sort_rows : bool, optional...
identifier_body
stata.py
import pandas as pd from larray.core.array import Array from larray.inout.pandas import from_frame __all__ = ['read_stata'] def
(filepath_or_buffer, index_col=None, sort_rows=False, sort_columns=False, **kwargs) -> Array: r""" Reads Stata .dta file and returns an Array with the contents Parameters ---------- filepath_or_buffer : str or file-like object Path to .dta file or a file handle. index_col : str or None,...
read_stata
identifier_name
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pip from pip.req import parse_requirements try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: hist...
'Programming Language :: Python :: 3.4', ], test_suite='tests', tests_require=test_requirements )
'Programming Language :: Python :: 3.3',
random_line_split
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not usi...
} else { Err(TryAccessError::Shutdown) } } /// Shut down the semaphore. /// /// This prevents any further access from being granted to the underlying resource. /// As soon as the last access is released and the returned handle goes out of scope, /// the resource wil...
{ Err(TryAccessError::NoCapacity) }
conditional_block
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not usi...
use parking_lot::RwLock; mod raw; use raw::RawSemaphore; mod guard; pub use guard::SemaphoreGuard; mod shutdown; pub use shutdown::ShutdownHandle; #[cfg(test)] mod tests; /// Result returned from `Semaphore::try_access`. pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>; #[derive(Copy, Clone...
random_line_split
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not usi...
#[inline] /// Attempt to access the underlying resource of this semaphore. /// /// This function will try to acquire access, and then return an RAII /// guard structure which will release the access when it falls out of scope. /// If the semaphore is out of capacity or shut down, a `TryAccessE...
{ Semaphore { raw: Arc::new(RawSemaphore::new(capacity)), resource: Arc::new(RwLock::new(Some(Arc::new(resource)))) } }
identifier_body
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not usi...
(&self) -> ShutdownHandle<T> { shutdown::new(&self.raw, self.resource.write().take()) } }
shutdown
identifier_name
pie_multiple_nesting.js
/* ------------------------------------------------------------------------------ * * # D3.js - multiple nested pie charts * * Demo d3.js multiple pie charts setup with nesting * * Version: 1.0 * Latest update: August 1, 2015 * * --------------------------------------------------------------------...
.style("text-anchor", "middle") .text(function(d) { return d.data.carrier; }); // Computes the label angle of an arc, converting from radians to degrees function angle(d) { var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; ...
random_line_split
pie_multiple_nesting.js
/* ------------------------------------------------------------------------------ * * # D3.js - multiple nested pie charts * * Demo d3.js multiple pie charts setup with nesting * * Version: 1.0 * Latest update: August 1, 2015 * * --------------------------------------------------------------------...
(element, radius, margin) { // Basic setup // ------------------------------ // Main variables var marginTop = 20; // Colors var colors = d3.scale.category20c(); // Load data // ------------------------------ d3.csv("assets/d...
pieMultipleNested
identifier_name
pie_multiple_nesting.js
/* ------------------------------------------------------------------------------ * * # D3.js - multiple nested pie charts * * Demo d3.js multiple pie charts setup with nesting * * Version: 1.0 * Latest update: August 1, 2015 * * --------------------------------------------------------------------...
});
{ // Basic setup // ------------------------------ // Main variables var marginTop = 20; // Colors var colors = d3.scale.category20c(); // Load data // ------------------------------ d3.csv("assets/demo_data/d3/pies/pies_nest...
identifier_body
animation.rs
// Copyright 2018 Google LLC // // 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 ...
{ Animation, InputOnly, } impl EventLoopMode { pub fn merge(self, other: EventLoopMode) -> EventLoopMode { match self { EventLoopMode::Animation => EventLoopMode::Animation, _ => other, } } } #[derive(Clone)] pub struct TimeLerp { started_at: Instant, d...
EventLoopMode
identifier_name
animation.rs
// Copyright 2018 Google LLC // // 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 ...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use map_model::Pt2D; use std::time::Instant; #[derive(PartialEq)] pub enum EventLoopMode { Animation, InputOnly, } impl EventLoo...
random_line_split
animation.rs
// Copyright 2018 Google LLC // // 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 ...
} #[derive(Clone)] pub struct TimeLerp { started_at: Instant, dur_s: f64, } impl TimeLerp { pub fn with_dur_s(dur_s: f64) -> TimeLerp { TimeLerp { dur_s, started_at: Instant::now(), } } fn elapsed(&self) -> f64 { let dt = self.started_at.elapsed();...
{ match self { EventLoopMode::Animation => EventLoopMode::Animation, _ => other, } }
identifier_body
bossanova.py
from __future__ import division """ These functions are for BOSSANOVA (BOss Survey of Satellites Around Nearby Optically obserVable milky way Analogs) """ import numpy as np from matplotlib import pyplot as plt import targeting def count_targets(hsts, verbose=True, remove_cached=True, rvir=300, targetingkwargs={})...
print 'Targeting parameters:', t sys.stdout.flush() tcat = targeting.select_targets(h, **t) cnts[j].append(len(tcat)) if remove_cached: h._cached_sdss = None t = table.Table() t.add_column(table.Column(name='name', data=nms)) t.a...
rvs.append(h.physical_to_projected(300)) for j, t in enumerate(targetingkwargs): if verbose:
random_line_split
bossanova.py
from __future__ import division """ These functions are for BOSSANOVA (BOss Survey of Satellites Around Nearby Optically obserVable milky way Analogs) """ import numpy as np from matplotlib import pyplot as plt import targeting def count_targets(hsts, verbose=True, remove_cached=True, rvir=300, targetingkwargs={})...
def generate_count_table(hsts, fnout=None, maglims=[21, 20.5, 20], outercutrad=-90,remove_cached=True): from astropy.io import ascii from astropy import table targetingkwargs = [] for m in maglims: targetingkwargs.append({'faintlimit': m, 'outercutrad': outercutrad, 'colname': str(m)}) ...
appmags = mwsatsrmags + h.distmod return np.sum(appmags < maglim)
identifier_body
bossanova.py
from __future__ import division """ These functions are for BOSSANOVA (BOss Survey of Satellites Around Nearby Optically obserVable milky way Analogs) """ import numpy as np from matplotlib import pyplot as plt import targeting def count_targets(hsts, verbose=True, remove_cached=True, rvir=300, targetingkwargs={})...
(h, maglim, mwsatsrmags=_sorted_mw_rabs): appmags = mwsatsrmags + h.distmod return np.sum(appmags < maglim) def generate_count_table(hsts, fnout=None, maglims=[21, 20.5, 20], outercutrad=-90,remove_cached=True): from astropy.io import ascii from astropy import table targetingkwargs = [] for m...
count_mw_sats
identifier_name
bossanova.py
from __future__ import division """ These functions are for BOSSANOVA (BOss Survey of Satellites Around Nearby Optically obserVable milky way Analogs) """ import numpy as np from matplotlib import pyplot as plt import targeting def count_targets(hsts, verbose=True, remove_cached=True, rvir=300, targetingkwargs={})...
if remove_cached: h._cached_sdss = None t = table.Table() t.add_column(table.Column(name='name', data=nms)) t.add_column(table.Column(name='distmpc', data=dists, units='Mpc')) t.add_column(table.Column(name='rvirarcmin', data=rvs, units='arcmin')) for cnm, cnt in zip(colnames...
if verbose: print 'Targeting parameters:', t sys.stdout.flush() tcat = targeting.select_targets(h, **t) cnts[j].append(len(tcat))
conditional_block
comment.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CommentBinding; use crate::dom::bindings::codegen::Bindings::WindowB...
(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> { let document = window.Document(); Ok(Comment::new(data, &document)) } }
Constructor
identifier_name
comment.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CommentBinding;
use crate::dom::characterdata::CharacterData; use crate::dom::document::Document; use crate::dom::node::Node; use crate::dom::window::Window; use dom_struct::dom_struct; /// An HTML comment. #[dom_struct] pub struct Comment { characterdata: CharacterData, } impl Comment { fn new_inherited(text: DOMString, doc...
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString;
random_line_split
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ ...
x = length; if x > 1 << 6 { x = 1 << 6; } dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2; dst[i + 1] = offset as u8; dst[i + 2] = (offset >> 8) as u8; i += 3; length -= x; } // (Future) Return a `Result<usize>` Instead?? i } // max_co...
{ dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; }
conditional_block
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ ...
while length > 0 { // TODO: Handle Overflow let mut x = length - 4; if 0 <= x && x < 1 << 3 && offset < 1 << 11 { dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; } ...
random_line_split
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ ...
(&mut self, src: &[u8]) -> Result<usize> { let mut written: usize = 0; if !self.wrote_header { // Write Stream Literal try!(self.inner.write(&MAGIC_CHUNK)); self.wrote_header = true; } // Split source into chunks of 65536 bytes each. for src...
write
identifier_name
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ ...
} // Compress writes the encoded form of src into dst and return the length // written. // Returns an error if dst was not large enough to hold the entire encoded // block. // (Future) Include a Legacy Compress?? pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> { if dst.len() < max_compressed_le...
{ self.inner.seek(pos).and_then(|res: u64| { self.pos = res; Ok(res) }) }
identifier_body
stagehand.js
/** * The MIT License (MIT) * * Copyright (c) 2013 Scott Will * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and t...
random_line_split
core.py
#!/usr/bin/env python import os import json class TermiteCore: def __init__( self, request, response ): self.request = request self.response = response def GetConfigs( self ): def GetServer(): return self.request.env['HTTP_HOST'] def GetDataset(): return self.request.application def GetModel...
folders = sorted( folders ) return folders def GetModels( dataset, model ): if dataset == 'init': return None app_data_path = '{}/data'.format( self.request.folder ) folders = [] for folder in os.listdir( app_data_path ): app_data_subpath = '{}/{}'.format( app_data_path, folder ) ...
folders.append( folder )
conditional_block
core.py
#!/usr/bin/env python import os import json class TermiteCore: def __init__( self, request, response ): self.request = request self.response = response def GetConfigs( self ): def GetServer(): return self.request.env['HTTP_HOST'] def GetDataset(): return self.request.application def GetModel...
( self, params = {}, keysAndValues = {} ): if self.IsDebugMode(): return self.GenerateDebugResponse() else: return self.GenerateNormalResponse( params, keysAndValues ) def GenerateDebugResponse( self ): def GetEnv( env ): data = {} for key in env: value = env[key] if isinstance( value, dict...
GenerateResponse
identifier_name
core.py
#!/usr/bin/env python import os import json class TermiteCore: def __init__( self, request, response ): self.request = request self.response = response def GetConfigs( self ): def GetServer(): return self.request.env['HTTP_HOST'] def GetDataset(): return self.request.application def GetModel...
def GetDatasets( dataset ): FOLDER_EXCLUSIONS = frozenset( [ 'admin', 'examples', 'welcome', 'init' ] ) applications_parent = self.request.env['applications_parent'] applications_path = '{}/applications'.format( applications_parent ) folders = [] for folder in os.listdir( applications_path ): a...
return self.request.function
identifier_body
core.py
#!/usr/bin/env python import os import json class TermiteCore: def __init__( self, request, response ): self.request = request self.response = response def GetConfigs( self ): def GetServer(): return self.request.env['HTTP_HOST'] def GetDataset(): return self.request.application def GetModel...
dataStr = json.dumps( data, encoding = 'utf-8', indent = 2, sort_keys = True ) # Workaround while we build up the server-client architecture self.response.headers['Access-Control-Allow-Origin'] = 'http://' + self.request.env['REMOTE_ADDR'] + ':8080' if self.IsJsonFormat(): return dataStr else: data[ ...
'configs' : self.GetConfigs() } data.update( keysAndValues )
random_line_split
name.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class NameService { constructor() { } getRandom() { let adjectiveIndex = Math.floor(Math.random() * 100) % ADJECTIVES.length, nounIndex = Math.floor(Math.random() * 100) % NOUNS.length; return `${ADJECTIVES[adjectiveI...
'land', 'lettuce', 'librarian', 'mortgage', 'mortuary', 'megaphone', 'nest', 'nematode', 'necromancer', 'octopus', 'orangutan', 'orbit', 'paleontologist', 'pacifier', 'peanut', 'queen', 'quicksilver', 'quirk', 'raisin', 'ranger', 'rasta...
'jello', 'jackalope', 'kangaroo', 'kroner', 'keychain',
random_line_split
name.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class
{ constructor() { } getRandom() { let adjectiveIndex = Math.floor(Math.random() * 100) % ADJECTIVES.length, nounIndex = Math.floor(Math.random() * 100) % NOUNS.length; return `${ADJECTIVES[adjectiveIndex]} ${NOUNS[nounIndex]}`; } } var ADJECTIVES = [ 'Able', 'Altered', ...
NameService
identifier_name
name.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class NameService { constructor()
getRandom() { let adjectiveIndex = Math.floor(Math.random() * 100) % ADJECTIVES.length, nounIndex = Math.floor(Math.random() * 100) % NOUNS.length; return `${ADJECTIVES[adjectiveIndex]} ${NOUNS[nounIndex]}`; } } var ADJECTIVES = [ 'Able', 'Altered', 'Awesome', 'Beaut...
{ }
identifier_body
map-queries-spec.js
'use babel'; import MapQueries from '../lib/map-queries'; // Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs. // // To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit` // or `fdescribe`). Remove the `f` to unfocus the block. describe('MapQueries', () => { let wor...
});
atom.commands.dispatch(workspaceElement, 'map-queries:toggle'); expect(mapQueriesElement).not.toBeVisible(); }); }); });
random_line_split
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) ...
} let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } ranges[index] = (b as usize, s as usize); index += 1; } index } pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsaf...
let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk);
random_line_split
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) ...
(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties().find(|p| p.name.conta...
diag_uart_range
identifier_name
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) ...
} pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let mut ranges: [(usize, usize); 10] = [(0,0); 10]; ...
{ 0 }
conditional_block
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) ...
pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties...
{ let memory_node = dt.find_node("/memory").unwrap(); let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let chunk_count = (reg.data.len() / chunk_sz); let mut index = 0; for chunk in reg.data.chunks(chunk_sz as usize) ...
identifier_body
v1.1.0.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restrict...
/// <reference path="../../_references.ts"/> module powerbi.extensibility.v110 { let overloadFactory: VisualVersionOverloadFactory = (visual: IVisual) => { return { update: (options: powerbi.VisualUpdateOptions) => { if (visual.update) { let updateOptions: V...
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
random_line_split
v1.1.0.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restrict...
} }; }; let hostAdapter: VisualHostAdapter = (host: powerbi.IVisualHostServices): IVisualHost => { return { createSelectionIdBuilder: () => new visuals.SelectionIdBuilder(), createSelectionManager: () => new SelectionManager({ hostServices: host }), ...
{ let updateOptions: VisualUpdateOptions = { viewport: options.viewport, dataViews: options.dataViews, type: v100.convertLegacyUpdateType(options) }; let transform: IVisualDataViewTransfo...
conditional_block
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var multer = require('multer') var app = express();
// uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(express.static(path.join(__dirname, 'public'))); app.use(logger('dev')); //app.use(multer({dest:'../public/uploads/'}).array('file')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded(...
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs');
random_line_split
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var multer = require('multer') var app = express(); // view engine setup app.set('views', path.join...
races leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
{ res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stackt
conditional_block