file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
CMapper.py
# -*- coding: utf-8 -*- dCellSize = 20 WindowWidth = 400 WindowHeight = 400 class SCell(object): def __init__(self, xmin, xmax, ymin, ymax): self._iTicksSpentHere = 0 self._left = xmin self._right = xmax self._top = ymin self.bottom = ymax def
(self): self._iTicksSpentHere += 1 def Reset(self): self._iTicksSpentHere = 0 class CMapper(object): def __init__(self, MaxRangeX, MaxRangeY): self._dCellSize = dCellSize self._NumCellsX = (MaxRangeX/self._dCellSize) + 1 self._NumCellsY = (MaxRangeY/self._dCellSize) + 1 self._2DvecCells = [] for x in...
Update
identifier_name
CMapper.py
# -*- coding: utf-8 -*- dCellSize = 20 WindowWidth = 400 WindowHeight = 400 class SCell(object): def __init__(self, xmin, xmax, ymin, ymax): self._iTicksSpentHere = 0 self._left = xmin self._right = xmax self._top = ymin self.bottom = ymax def Update(self): self._iTicksSpentHere...
for j in xrange(self._NumCellsY): if self._2DvecCells[i][j]._iTicksSpentHere > 0: total += 1 return total
total = 0 for i in xrange(self._NumCellsX):
random_line_split
CMapper.py
# -*- coding: utf-8 -*- dCellSize = 20 WindowWidth = 400 WindowHeight = 400 class SCell(object): def __init__(self, xmin, xmax, ymin, ymax): self._iTicksSpentHere = 0 self._left = xmin self._right = xmax self._top = ymin self.bottom = ymax def Update(self): self._iTicksSpentHere...
def Render(self): print "To be implemented" def Reset(self): for i in xrange(self._NumCellsX): for j in xrange(self._NumCellsY): self._2DvecCells[i][j].Reset() def NumCellsVisited(self): total = 0 for i in xrange(self._NumCellsX): for j in xrange(self._NumCellsY): if self._2DvecCells[i][j]....
print "Not implemented!"
identifier_body
CMapper.py
# -*- coding: utf-8 -*- dCellSize = 20 WindowWidth = 400 WindowHeight = 400 class SCell(object): def __init__(self, xmin, xmax, ymin, ymax): self._iTicksSpentHere = 0 self._left = xmin self._right = xmax self._top = ymin self.bottom = ymax def Update(self): self._iTicksSpentHere...
def NumCellsVisited(self): total = 0 for i in xrange(self._NumCellsX): for j in xrange(self._NumCellsY): if self._2DvecCells[i][j]._iTicksSpentHere > 0: total += 1 return total
self._2DvecCells[i][j].Reset()
conditional_block
indexedcorpus.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Base Indexed Corpus class.""" import logging import numpy from gensim import interfaces, utils logger = logging.getLogger(__name...
if index_fname is None: index_fname = utils.smart_extension(fname, '.index') kwargs = {'metadata': metadata} if progress_cnt is not None: kwargs['progress_cnt'] = progress_cnt if labels is not None: kwargs['labels'] = labels offsets = seri...
raise ValueError("identical input vs. output corpus filename, refusing to serialize: %s" % fname)
conditional_block
indexedcorpus.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Base Indexed Corpus class.""" import logging import numpy from gensim import interfaces, utils logger = logging.getLogger(__name...
(self, fname, index_fname=None): """ Parameters ---------- fname : str Path to corpus. index_fname : str, optional Path to index, if not provided - used `fname.index`. """ try: if index_fname is None: index_fna...
__init__
identifier_name
indexedcorpus.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Base Indexed Corpus class.""" import logging import numpy from gensim import interfaces, utils logger = logging.getLogger(__name...
>>> doc = corpus[document_index] Notes ----- This functionality is achieved by storing an extra file (by default named the same as the `fname.index`) that stores the byte offset of the beginning of each document. """ def __init__(self, fname, index_fname=None): """ Pa...
"""Indexed corpus is a mechanism for random-accessing corpora. While the standard corpus interface in gensim allows iterating over corpus, we'll show it with :class:`~gensim.corpora.mmcorpus.MmCorpus`. .. sourcecode:: pycon >>> from gensim.corpora import MmCorpus >>> from gensim.test.util...
identifier_body
indexedcorpus.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Base Indexed Corpus class."""
from gensim import interfaces, utils logger = logging.getLogger(__name__) class IndexedCorpus(interfaces.CorpusABC): """Indexed corpus is a mechanism for random-accessing corpora. While the standard corpus interface in gensim allows iterating over corpus, we'll show it with :class:`~gensim.corpora.mmco...
import logging import numpy
random_line_split
remutex.rs
// Copyright 2015 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 ...
self) -> TryLockResult<ReentrantMutexGuard<T>> { if unsafe { self.inner.try_lock() } { Ok(try!(ReentrantMutexGuard::new(&self))) } else { Err(TryLockError::WouldBlock) } } } impl<T> Drop for ReentrantMutex<T> { fn drop(&mut self) { // This is actually saf...
y_lock(&
identifier_name
remutex.rs
// Copyright 2015 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 ...
lse { Err(TryLockError::WouldBlock) } } } impl<T> Drop for ReentrantMutex<T> { fn drop(&mut self) { // This is actually safe b/c we know that there is no further usage of // this mutex (it's up to the user to arrange for a mutex to get // dropped, that's not our job)...
Ok(try!(ReentrantMutexGuard::new(&self))) } e
conditional_block
remutex.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let c = m.lock().unwrap(); assert_eq!(*c, ()); } assert_eq!(*b, ()); } assert_eq!(*a, ()); } } #[test] fn is_mutex() { let m = Arc::new(ReentrantMutex::new(RefCell::new(0))); ...
{ let b = m.lock().unwrap();
random_line_split
remutex.rs
// Copyright 2015 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 ...
impl<'mutex, T> ReentrantMutexGuard<'mutex, T> { fn new(lock: &'mutex ReentrantMutex<T>) -> LockResult<ReentrantMutexGuard<'mutex, T>> { poison::map_result(lock.poison.borrow(), |guard| { ReentrantMutexGuard { __lock: lock, __poison: guard, ...
match self.try_lock() { Ok(guard) => write!(f, "ReentrantMutex {{ data: {:?} }}", &*guard), Err(TryLockError::Poisoned(err)) => { write!(f, "ReentrantMutex {{ data: Poisoned({:?}) }}", &**err.get_ref()) }, Err(TryLockError::WouldBlock) => write!(f,...
identifier_body
buffer.rs
use std::ffi::c_void; use std::cell::Cell; use std::fmt; use std::ops::Deref; pub unsafe trait BufferType: ::lv2::core::PortType { type BufferImpl: PortBuffer + 'static; } pub unsafe trait PortBuffer { fn get_ptr(&self) -> *mut c_void; fn get_size(&self) -> usize; } #[derive(Clone, Default)] pub struct C...
dst.set(src) } } } unsafe impl<T: Copy> PortBuffer for VecBuffer<T> { #[inline] fn get_ptr(&self) -> *mut c_void { self.inner.as_ptr() as _ } #[inline] fn get_size(&self) -> usize { self.inner.len() } // type BufferType = SampleDependentBufferType<T...
pub fn set_all<I: IntoIterator<Item=T>>(&self, iter: I) { for (src, dst) in iter.into_iter().zip(&self.inner) {
random_line_split
buffer.rs
use std::ffi::c_void; use std::cell::Cell; use std::fmt; use std::ops::Deref; pub unsafe trait BufferType: ::lv2::core::PortType { type BufferImpl: PortBuffer + 'static; } pub unsafe trait PortBuffer { fn get_ptr(&self) -> *mut c_void; fn get_size(&self) -> usize; } #[derive(Clone, Default)] pub struct C...
// type BufferType = SampleDependentBufferType<T>; } impl<T: Copy + fmt::Debug> fmt::Debug for VecBuffer<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Debug::fmt(&self.get(), f) } } unsafe impl BufferType for ::lv2::core::ports::Audio { type BufferImpl = VecBuff...
{ self.inner.len() }
identifier_body
buffer.rs
use std::ffi::c_void; use std::cell::Cell; use std::fmt; use std::ops::Deref; pub unsafe trait BufferType: ::lv2::core::PortType { type BufferImpl: PortBuffer + 'static; } pub unsafe trait PortBuffer { fn get_ptr(&self) -> *mut c_void; fn get_size(&self) -> usize; } #[derive(Clone, Default)] pub struct C...
(&self, value: T) { self.inner.replace(value); } } unsafe impl<T: Copy> PortBuffer for CellBuffer<T> { #[inline] fn get_ptr(&self) -> *mut c_void { self.inner.as_ptr() as _ } #[inline] fn get_size(&self) -> usize { 1 } } unsafe impl BufferType for ::lv2::core::port...
set
identifier_name
queue_processors.py
from django.core.mail import EmailMessage from zerver.lib.redis_utils import get_redis_client import os import sys import ujson from collections import defaultdict import email import time import datetime import logging import simplejson import StringIO def assign_queue(queue_name, enabled=True): def decorate(cl...
def stop(self): self.q.stop_consuming() if settings.MAILCHIMP_API_KEY: from postmonkey import PostMonkey, MailChimpException @assign_queue('signups') class SignupWorker(QueueProcessingWorker): def __init__(self): super(SignupWorker, self).__init__() if settings.MAILCHIMP_API_KEY:...
self.q.register_json_consumer(self.queue_name, self.consume_wrapper) self.q.start_consuming()
identifier_body
queue_processors.py
from django.core.mail import EmailMessage from zerver.lib.redis_utils import get_redis_client import os import sys import ujson from collections import defaultdict import email import time import datetime import logging import simplejson import StringIO def assign_queue(queue_name, enabled=True): def decorate(cl...
if len(slow_queries) > 0: topic = "%s: slow queries" % (settings.STATSD_PREFIX,) content = "" for query in slow_queries: content += " %s\n" % (query,) internal_send_message(settings.ERROR_BOT, "stream", "logs", topic, content) reset...
return
conditional_block
queue_processors.py
, MailChimpException @assign_queue('signups') class SignupWorker(QueueProcessingWorker): def __init__(self): super(SignupWorker, self).__init__() if settings.MAILCHIMP_API_KEY: self.pm = PostMonkey(settings.MAILCHIMP_API_KEY, timeout=10) def consume(self, data): merge_vars=...
consume
identifier_name
queue_processors.py
from django.core.mail import EmailMessage from zerver.lib.redis_utils import get_redis_client import os import sys import ujson from collections import defaultdict import email import time
def assign_queue(queue_name, enabled=True): def decorate(clazz): clazz.queue_name = queue_name if enabled: register_worker(queue_name, clazz) return clazz return decorate worker_classes = {} def register_worker(queue_name, clazz): worker_classes[queue_name] = clazz def ...
import datetime import logging import simplejson import StringIO
random_line_split
5396-fnUpdate-arrays-mData.js
// DATA_TEMPLATE: empty_table oTest.fnStart("5396 - fnUpdate with 2D arrays for a single row"); $(document).ready(function () { $('#example thead tr').append('<th>6</th>'); $('#example thead tr').append('<th>7</th>'); $('#example thead tr').append('<th>8</th>'); $('#example thead tr').append('<th>9</th...
{ "mData": "0"}, { "mData": "1"}, { "mData": "2"}, { "mData": "3"}, { "mData": "4.0.0"}, { "mData": "4.0.1"}, { "mData": "4.1.0"}, { "mData": "4.1.1"}, { "mData": "5"}, { "mData": "6"} ] }...
] var oTable = $('#example').dataTable({ "aaData": aDataSet, "aoColumns": [
random_line_split
proxy_checker.py
# -*- coding: UTF-8 -*- #!/usr/bin/env python from __future__ import unicode_literals # ------------------------------------------------------------------------------ # Name: Proxy checker # Purpose: Just a couple of functions to check various proxy configuration # # Author: Julien Moura (@geojulien)...
(pip): """ TO COMMENT """ try: proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib2.install_opener(opener) req=urllib2.Request('http://www.example.com') # chan...
is_bad_proxy
identifier_name
proxy_checker.py
# -*- coding: UTF-8 -*- #!/usr/bin/env python from __future__ import unicode_literals # ------------------------------------------------------------------------------ # Name: Proxy checker # Purpose: Just a couple of functions to check various proxy configuration # # Author: Julien Moura (@geojulien)...
############################################################################### ########### Libraries ############# ################################### # Standard library import urllib2 import socket import sys import string import os # 3rd party libraries import arcpy ###############################################...
# -----------------------------------------------------------------------------
random_line_split
proxy_checker.py
# -*- coding: UTF-8 -*- #!/usr/bin/env python from __future__ import unicode_literals # ------------------------------------------------------------------------------ # Name: Proxy checker # Purpose: Just a couple of functions to check various proxy configuration # # Author: Julien Moura (@geojulien)...
def main(): """ TO COMMENT """ socket.setdefaulttimeout(120) # two sample proxy IPs proxyList = ['10.0.4.2:3128', '{0}:{1}'.format(prox, port), '{0}://{1}:{2}@{3}:{4}'.format(protocole, user, password, prox, port)] for currentProxy in proxyList: if is_bad_proxy(c...
""" TO COMMENT """ try: proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib2.install_opener(opener) req=urllib2.Request('http://www.example.com') # change the URL ...
identifier_body
proxy_checker.py
# -*- coding: UTF-8 -*- #!/usr/bin/env python from __future__ import unicode_literals # ------------------------------------------------------------------------------ # Name: Proxy checker # Purpose: Just a couple of functions to check various proxy configuration # # Author: Julien Moura (@geojulien)...
else: print "%s is working" % (currentProxy) arcpy.AddMessage("is working") ############################################################################### ###### Stand alone program ######## ################################### if __name__ == '__main__': """ standalone execution f...
print "Bad Proxy %s" % (currentProxy) arcpy.AddMessage("Bad Proxy")
conditional_block
converge.js
var _curry2 = require('./internal/_curry2'); var _map = require('./internal/_map'); var curryN = require('./curryN'); var pluck = require('./pluck'); /** * Accepts a converging function and a list of branching functions and returns a new function. * When invoked, this new function is applied to some arguments, each...
* * @func * @memberOf R * @since v0.4.2 * @category Function * @sig (x1 -> x2 -> ... -> z) -> [(a -> b -> ... -> x1), (a -> b -> ... -> x2), ...] -> (a -> b -> ... -> z) * @param {Function} after A function. `after` will be invoked with the return values of * `fn1` and `fn2` as its arguments. * @param {...
random_line_split
part1.rs
// adventofcode - day 9 // part 1 use std::io::prelude::*; use std::fs::File; use std::collections::HashSet; struct Graph { nodes: Option<Vec<String>>, matrix: Option<Vec<Vec<i32>>>, } impl Graph { fn new(names: HashSet<&str>) -> Graph { let mut graph = Graph{nodes: None, matrix: None}; ...
{ let mut file = match File::open("../../inputs/09.txt") { Ok(f) => f, Err(e) => panic!("file error: {}", e), }; let mut data = String::new(); match file.read_to_string(&mut data){ Ok(_) => {}, Err(e) => panic!("file error: {}", e), }; // remove trailing \n ...
identifier_body
part1.rs
// adventofcode - day 9 // part 1 use std::io::prelude::*; use std::fs::File; use std::collections::HashSet; struct Graph { nodes: Option<Vec<String>>, matrix: Option<Vec<Vec<i32>>>, } impl Graph { fn new(names: HashSet<&str>) -> Graph { let mut graph = Graph{nodes: None, matrix: None}; ...
.collect::<Vec<String>>(); let length = info[2].parse::<i32>().unwrap(); graph.insert_edge(&info[0], &info[1], length); } Some(graph) } // This function simply imports the data set from a file called input.txt fn import_data() -> String { let mut file =...
for line in data.lines(){ let info = line.split(" to ") .flat_map(|s| s.split(" = ")) .map(|s| s.parse::<String>().unwrap())
random_line_split
part1.rs
// adventofcode - day 9 // part 1 use std::io::prelude::*; use std::fs::File; use std::collections::HashSet; struct Graph { nodes: Option<Vec<String>>, matrix: Option<Vec<Vec<i32>>>, } impl Graph { fn new(names: HashSet<&str>) -> Graph { let mut graph = Graph{nodes: None, matrix: None}; ...
() -> String { let mut file = match File::open("../../inputs/09.txt") { Ok(f) => f, Err(e) => panic!("file error: {}", e), }; let mut data = String::new(); match file.read_to_string(&mut data){ Ok(_) => {}, Err(e) => panic!("file error: {}", e), }; // remove tra...
import_data
identifier_name
auth.js
/** * vim:set sw=2 ts=2 sts=2 ft=javascript expandtab: * * # Authentification module * * ## License * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership...
xhr.setRequestHeader('Authorization', 'JWT ' + auth.token()); }; return auth; }).call(this);
*/ auth.fn.xhrConfig = function (xhr) {
random_line_split
Operation.js
/*! @license Firebase v4.5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OperationSource = exports.OperationType = undefined; var _assert = require("../../../utils/assert"); /** * * @enum */ var OperationTy...
/** * @const * @type {!OperationSource} */ OperationSource.User = new OperationSource( /*fromUser=*/true, false, null, /*tagged=*/false); /** * @const * @type {!OperationSource} */ OperationSource.Server = new OperationSource(false, /*fromServer=*/true, null, /*tagged=*/false); /** ...
{ this.fromUser = fromUser; this.fromServer = fromServer; this.queryId = queryId; this.tagged = tagged; (0, _assert.assert)(!tagged || fromServer, 'Tagged queries must be from server.'); }
identifier_body
Operation.js
/*! @license Firebase v4.5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OperationSource = exports.OperationType = undefined; var _assert = require("../../../utils/assert"); /** * * @enum */ var OperationTy...
*/ var OperationSource = /** @class */function () { function OperationSource(fromUser, fromServer, queryId, tagged) { this.fromUser = fromUser; this.fromServer = fromServer; this.queryId = queryId; this.tagged = tagged; (0, _assert.assert)(!tagged || fromServer, 'Tagged queries must be from serve...
* @param {boolean} tagged * @constructor
random_line_split
Operation.js
/*! @license Firebase v4.5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OperationSource = exports.OperationType = undefined; var _assert = require("../../../utils/assert"); /** * * @enum */ var OperationTy...
(fromUser, fromServer, queryId, tagged) { this.fromUser = fromUser; this.fromServer = fromServer; this.queryId = queryId; this.tagged = tagged; (0, _assert.assert)(!tagged || fromServer, 'Tagged queries must be from server.'); } /** * @const * @type {!OperationSource} */ OperationSour...
OperationSource
identifier_name
step7_quote.rs
::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new...
return Ok(tmp.clone()); } let ref a0 = *args[0]; match *a0 { Sym(ref a0sym) => (args, &a0sym[..]), _ => (args, "__<fn*>__"), } }, _ => return err_str("Expected list"), }; match a0sym { "def!"...
{ 'tco: loop { //println!("eval: {}, {}", ast, env.borrow()); //println!("eval: {}", ast); match *ast { List(_,_) => (), // continue _ => return eval_ast(ast, env), } // apply list match *ast { List(_,_) => (), // continue _ => return Ok(ast), } l...
identifier_body
step7_quote.rs
::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new...
(x: MalVal) -> bool { match *x { List(ref lst,_) | Vector(ref lst,_) => lst.len() > 0, _ => false, } } fn quasiquote(ast: MalVal) -> MalVal { if !is_pair(ast.clone()) { return list(vec![symbol("quote"), ast]) } match *ast.clone() { List(ref args,_) | Vector(ref args...
is_pair
identifier_name
step7_quote.rs
::{MalVal, MalRet, MalError, err_str}; use mal::types::{symbol, _nil, string, list, vector, hash_map, malfunc}; use mal::types::MalError::{ErrString, ErrMalVal}; use mal::types::MalType::{Nil, False, Sym, List, Vector, Hash_Map, Func, MalFunc}; use mal::{readline, reader, core}; use mal::env::{env_set, env_get, env_new...
return list(vec![symbol("quote"), ast]) } match *ast.clone() { List(ref args,_) | Vector(ref args,_) => { let ref a0 = args[0]; match **a0 { Sym(ref s) if *s == "unquote" => return args[1].clone(), _ => (), } if is_...
fn quasiquote(ast: MalVal) -> MalVal { if !is_pair(ast.clone()) {
random_line_split
main.rs
extern crate graphics; extern crate freetype as ft; extern crate opengl_graphics; extern crate piston; extern crate find_folder; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")] extern crate glutin_window; #[cfg(fe...
).unwrap(); res.push((texture, [(x + g.bitmap_left()) as f64, (y - g.bitmap_top()) as f64])); x += (g.advance().x >> 6) as i32; y += (g.advance().y >> 6) as i32; } res } fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G) where G: Graphics<Texture = T>, ...
let texture = Texture::from_memory_alpha( bitmap.buffer(), bitmap.width() as u32, bitmap.rows() as u32, &TextureSettings::new()
random_line_split
main.rs
extern crate graphics; extern crate freetype as ft; extern crate opengl_graphics; extern crate piston; extern crate find_folder; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")] extern crate glutin_window; #[cfg(fe...
res } fn render_text<G, T>(glyphs: &[(T, [f64; 2])], c: &Context, gl: &mut G) where G: Graphics<Texture = T>, T: ImageSize { for &(ref texture, [x, y]) in glyphs { use graphics::*; Image::new_color(color::BLACK).draw( texture, &c.draw_state, c.transform...
{ let mut x = 10; let mut y = 0; let mut res = vec![]; for ch in text.chars() { face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Texture::from_memory_alpha( bitmap.buffer(), ...
identifier_body
main.rs
extern crate graphics; extern crate freetype as ft; extern crate opengl_graphics; extern crate piston; extern crate find_folder; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")] extern crate glutin_window; #[cfg(fe...
} }
{ use graphics::*; gl.draw(args.viewport(), |c, gl| { clear(color::WHITE, gl); render_text(&glyphs, &c.trans(0.0, 100.0), gl); }); }
conditional_block
main.rs
extern crate graphics; extern crate freetype as ft; extern crate opengl_graphics; extern crate piston; extern crate find_folder; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")] extern crate glutin_window; #[cfg(fe...
(face: &mut ft::Face, text: &str) -> Vec<(Texture, [f64; 2])> { let mut x = 10; let mut y = 0; let mut res = vec![]; for ch in text.chars() { face.load_char(ch as usize, ft::face::LoadFlag::RENDER).unwrap(); let g = face.glyph(); let bitmap = g.bitmap(); let texture = Te...
glyphs
identifier_name
regress-373827-01.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-373827-01...
let ([] = [{x: function(){}}]) { }; reportCompare(expect, actual, summary); exitFunc ('test'); }
enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary);
random_line_split
regress-373827-01.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-373827-01...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); let ([] = [{x: function(){}}]) { }; reportCompare(expect, actual, summary); exitFunc ('test'); }
identifier_body
regress-373827-01.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-373827-01...
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); let ([] = [{x: function(){}}]) { }; reportCompare(expect, actual, summary); exitFunc ('test'); }
test
identifier_name
test_aws.py
import pytest from mock import patch, call, Mock, MagicMock from blt.tools import aws @pytest.fixture def
(): config = { "aws": { "AWS_ACCESS_KEY_ID": "JLKSNLBNLSKDFJWOEI" , "AWS_SECRET_ACCESS_KEY": "JFvnwoaifeIOJFnegoiwfaqEF" , "AWS_BUCKET_NAME": "matter-developers" , "SOURCE_FOLDER": "/Users/coldwd/data/pubweb/static_assets/" , "AWS_FOLDER_PREFIX": "dencold/" ...
cmds
identifier_name
test_aws.py
import pytest from mock import patch, call, Mock, MagicMock from blt.tools import aws @pytest.fixture def cmds(): config = { "aws": { "AWS_ACCESS_KEY_ID": "JLKSNLBNLSKDFJWOEI" , "AWS_SECRET_ACCESS_KEY": "JFvnwoaifeIOJFnegoiwfaqEF" , "AWS_BUCKET_NAME": "matter-developers" ...
assert len(aws.upload_file.mock_calls) == 2 aws.upload_file.assert_has_calls(calls) def test_get_changed_files(source_hashes, target_hashes): changed_files = aws.get_changed_files(source_hashes, target_hashes) assert sorted(changed_files) == [ 'images/diff_hash.jpg', 'images/dne.jpg']
cmds._get_s3_bucket = Mock() bucket = Mock() cmds._get_s3_bucket.return_value = bucket # these need to be switched to patches...they affect *all* test methods aws.get_hashes_from_dirtree = Mock(return_value=source_hashes()) aws.get_hashes_from_s3bucket = Mock(return_value=target_hashes()) aws.u...
identifier_body
test_aws.py
import pytest from mock import patch, call, Mock, MagicMock from blt.tools import aws @pytest.fixture def cmds(): config = { "aws": { "AWS_ACCESS_KEY_ID": "JLKSNLBNLSKDFJWOEI" , "AWS_SECRET_ACCESS_KEY": "JFvnwoaifeIOJFnegoiwfaqEF" , "AWS_BUCKET_NAME": "matter-developers" ...
# -- Test Cases! -------------------------------------------------------------- def test_sync_s3(cmds): # setup mocks cmds._get_s3_bucket = Mock() bucket = Mock() cmds._get_s3_bucket.return_value = bucket # these need to be switched to patches...they affect *all* test methods aws.get_hashes_fr...
def teardown_function(function): """this is called after every test case runs""" aws.local.reset_mock() aws.boto.reset_mock()
random_line_split
1.4.1.py
#coding:utf-8 ''' 第一种方式:使用os模块中的fork方式实现多进程 import os if __name__ == '__main__': print 'current Process (%s) start ...'%(os.getpid()) pid = os.fork() if pid < 0: print 'error in fork' elif pid == 0: print 'I am child process(%s) and my parent process is (%s)',(os.getpid(),os.getppid()) ...
'''
random_line_split
navigator.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::Na...
(&self) -> DOMString { navigatorinfo::Language() } // https://html.spec.whatwg.org/multipage/#dom-navigator-plugins fn Plugins(&self) -> Root<PluginArray> { self.plugins.or_init(|| PluginArray::new(self.global().r())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimet...
Language
identifier_name
navigator.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::Na...
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform fn Platform(&self) -> DOMString { navigatorinfo::Platform() } // https://html.spec.whatwg.org/multipage/#dom-navigator-useragent fn UserAgent(&self) -> DOMString { navigatorinfo::UserAgent() } // https://ht...
{ navigatorinfo::AppCodeName() }
identifier_body
navigator.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Refle...
random_line_split
conf.py
import os from ConfigParser import ConfigParser from amlib import argp tmp_conf = ConfigParser() tmp_path = os.path.dirname(os.path.abspath(__file__)) # /base/lib/here tmp_path = tmp_path.split('/') conf_path = '/'.join(tmp_path[0:-1]) # /base/lib tmp_conf.read(conf_path+'/ampush.conf') c = {} c.update(tmp_conf.ite...
c['flat_file_map_dir'] = c['flat_file_map_dir_default']
else:
random_line_split
conf.py
import os from ConfigParser import ConfigParser from amlib import argp tmp_conf = ConfigParser() tmp_path = os.path.dirname(os.path.abspath(__file__)) # /base/lib/here tmp_path = tmp_path.split('/') conf_path = '/'.join(tmp_path[0:-1]) # /base/lib tmp_conf.read(conf_path+'/ampush.conf') c = {} c.update(tmp_conf.ite...
else: c['flat_file_map_dir'] = c['flat_file_map_dir_default']
try: ff_map_dir_conf_key = 'flat_file_map_dir_' + argp.a['source'] c['flat_file_map_dir'] = c[ff_map_dir_conf_key] except KeyError: log_msg = 'Terminating. No such parameter in ampush.conf: ' + \ ff_map_dir_conf_key raise Exception(log_msg)
conditional_block
slack.py
#!/usr/bin/env python3 # # Copyright (c) 2017 Nick Douma # # 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,...
parser = ArgumentParser(description="Send notifications using Slack") parser.add_argument("--webhook-url", help="Webhook URL.", required=True) parser.add_argument("--channel", help="Channel to post to (prefixed with #), " "or a specific user (prefixed with @).") parser.add_argument("--username", ...
value = value.replace("#", "") if not re.match(r"^[a-f0-9]{6}$", value): raise ArgumentTypeError("Argument is not a valid hex value.") return value
identifier_body
slack.py
#!/usr/bin/env python3 # # Copyright (c) 2017 Nick Douma # # 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,...
attachment = {} for param in ["title", "title_link", "color", "ts", "message"]: value = getattr(args, param) if value: attachment[param] = value attachment['fallback'] = attachment['message'] attachment['text'] = attachment['message'] del attachment['message'] message['attachments'] = [attachment] p...
message[param] = value
conditional_block
slack.py
#!/usr/bin/env python3 # # Copyright (c) 2017 Nick Douma # # 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,...
(value): value = value.replace("#", "") if not re.match(r"^[a-f0-9]{6}$", value): raise ArgumentTypeError("Argument is not a valid hex value.") return value parser = ArgumentParser(description="Send notifications using Slack") parser.add_argument("--webhook-url", help="Webhook URL.", required=True...
hex_value
identifier_name
slack.py
#!/usr/bin/env python3 # # Copyright (c) 2017 Nick Douma # # 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,...
*[int(m) for m in matches.groups()])).timestamp() def hex_value(value): value = value.replace("#", "") if not re.match(r"^[a-f0-9]{6}$", value): raise ArgumentTypeError("Argument is not a valid hex value.") return value parser = ArgumentParser(description="Send notifications using Slack"...
if not matches: raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 " "timestamp.") return int(datetime.datetime(
random_line_split
precision_recall.py
import matplotlib.pyplot as plt import numpy as np import sklearn from sklearn import svm, datasets from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from sklearn.cross_validation import train_test_split from sklearn.preprocessing import label_binarize from sklearn.m...
# now do decision trees model = tree.DecisionTreeClassifier() classifier = OneVsRestClassifier(model) y_score = classifier.fit(X_train, y_train).decision_function(X_test) # Compute Precision-Recall and plot curve precision[5], recall[5], _ = precision_recall_curve(y_test, y_score) average_precision[5] = average_precis...
precision[4], recall[4], _ = precision_recall_curve(y_test, y_score) average_precision[4] = average_precision_score(y_test, y_score)
random_line_split
precision_recall.py
import matplotlib.pyplot as plt import numpy as np import sklearn from sklearn import svm, datasets from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from sklearn.cross_validation import train_test_split from sklearn.preprocessing import label_binarize from sklearn.m...
plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Classification on aggregate crime; precision vs. recall') plt.legend(loc="lower right") plt.show()
plt.plot(recall[i], precision[i], label='Precision-recall curve of {0} (area = {1:0.2f})' ''.format(kernel[i], average_precision[i]))
conditional_block
robotsParser.js
var robotsParser = require("robots-parser"), urlMod = require("url"); /** * This is a parse that analyzes URL with path /robots.txt. * * @return {Function} Returns the handler. */ module.exports = function (opts) { if (!opts) { opts = {}; } if (!opts.urlFilter)
return function (context) { var robots, urlObj; urlObj = urlMod.parse(context.url); // skip if this is not actually a robots.txt file. if (urlObj.pathname !== "/robots.txt") { return []; } robots = robotsParser(context.url, context.body.toString()); return robots.getSit...
{ opts.urlFilter = function () { return true; }; }
conditional_block
robotsParser.js
var robotsParser = require("robots-parser"), urlMod = require("url"); /** * This is a parse that analyzes URL with path /robots.txt. * * @return {Function} Returns the handler. */ module.exports = function (opts) { if (!opts) { opts = {}; } if (!opts.urlFilter) { opts.urlFilter = function () { ...
}).filter(function (sitemapUrl) { return opts.urlFilter(sitemapUrl, context.url); }); }; };
random_line_split
fsutil.js
var fs = require('fs'); var scErrors = require('sc-errors'); var TimeoutError = scErrors.TimeoutError; var fileExists = function (filePath, callback) { fs.access(filePath, fs.constants.F_OK, (err) => { callback(!err); }); }; var waitForFile = function (filePath, checkInterval, startTime, maxWaitDuration, time...
} else { errorMessage = `Could not find a file at path ${filePath} ` + `before the timeout was reached`; } var volumeBootTimeoutError = new TimeoutError(errorMessage); reject(volumeBootTimeoutError); } else { setTimeout(ch...
errorMessage = timeoutErrorMessage;
random_line_split
fsutil.js
var fs = require('fs'); var scErrors = require('sc-errors'); var TimeoutError = scErrors.TimeoutError; var fileExists = function (filePath, callback) { fs.access(filePath, fs.constants.F_OK, (err) => { callback(!err); }); }; var waitForFile = function (filePath, checkInterval, startTime, maxWaitDuration, time...
} }); }; checkIsReady(); }); }; module.exports = { fileExists: fileExists, waitForFile: waitForFile };
{ setTimeout(checkIsReady, checkInterval); }
conditional_block
build.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::process::Command; // this build script is called on en every `devtool build`, // embedding the FIRECRACKER_VERSION directly in the resulting binary fn
() { let firecracker_version = Command::new("git") .args(&["describe", "--dirty"]) .output() .ok() .and_then(|output| { if output.status.success() { return Some(output.stdout); } None }) .and_then(|version_bytes| Str...
main
identifier_name
build.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0
// this build script is called on en every `devtool build`, // embedding the FIRECRACKER_VERSION directly in the resulting binary fn main() { let firecracker_version = Command::new("git") .args(&["describe", "--dirty"]) .output() .ok() .and_then(|output| { if output.stat...
use std::process::Command;
random_line_split
build.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::process::Command; // this build script is called on en every `devtool build`, // embedding the FIRECRACKER_VERSION directly in the resulting binary fn main()
{ let firecracker_version = Command::new("git") .args(&["describe", "--dirty"]) .output() .ok() .and_then(|output| { if output.status.success() { return Some(output.stdout); } None }) .and_then(|version_bytes| String...
identifier_body
build.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::process::Command; // this build script is called on en every `devtool build`, // embedding the FIRECRACKER_VERSION directly in the resulting binary fn main() { let firecracker_version = Comma...
None }) .and_then(|version_bytes| String::from_utf8(version_bytes).ok()) .map(|version_string| version_string.trim_start_matches('v').to_string()) .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string()); println!( "cargo:rustc-env=FIRECRACKER_VERSION={}", ...
{ return Some(output.stdout); }
conditional_block
vehicle-payload.js
/** * Vehicle payload * * LIGNA scenario: step 15 * * Display description: - A chart of the vehicle payload for the current day * * Input variables: - machine[mid].technical_data.vehicle_payload * * @@source_header * * -- * * This file is part of the focus-app-demonstrator package. * * For the full...
angular.copy(new_data[0], _self.chartData[0].data); angular.copy(new_data[1], _self.chartData[1].data); }; _self.drawDynamicData(); /** * Register refresh callback */ DataService.registerRefreshCallback(_self.drawDynamicData); } ]); }());
{ _self.last_values.push({ date: new_data[0][last_elem - i*30][0], value: new_data[0][last_elem - i*30][1] }); }
conditional_block
vehicle-payload.js
/** * Vehicle payload * * LIGNA scenario: step 15 * * Display description: - A chart of the vehicle payload for the current day * * Input variables: - machine[mid].technical_data.vehicle_payload * * @@source_header * * -- * * This file is part of the focus-app-demonstrator package. * * For the full...
/** * Initialize everything. */ var _init = function() { // infer max value for yAxis var max_value = 10000 * 1.3; angular .forEach( DataService.dataSet.timedependent['<TIME:machine[' + _self.currentMachineId + '].technical_data.vehicle_payload>'], fu...
* Table with latest values */ _self.last_values = [];
random_line_split
TableFieldSettings.js
(function($) { Craft.TableFieldSettings = Garnish.Base.extend( { columnsTableName: null, defaultsTableName: null, columnsTableId: null, defaultsTableId: null, columnsTableInputPath: null, defaultsTableInputPath: null, defaults: null, columnSettings: null, columnsTable: null, defaultsTable: null, init: f...
for (var i = 0; i < this.defaultsTableInputPath.length; i++) { var key = this.defaultsTableInputPath[i]; defaults = defaults[key]; } var tableHtml = '<table id="'+this.defaultsTableId+'" class="editable shadow-box">' + '<thead>' + '<tr>'; for (var colId in columns) { tableHtml += '<th sc...
{ var key = this.columnsTableInputPath[i]; columns = columns[key]; }
conditional_block
TableFieldSettings.js
Craft.TableFieldSettings = Garnish.Base.extend( { columnsTableName: null, defaultsTableName: null, columnsTableId: null, defaultsTableId: null, columnsTableInputPath: null, defaultsTableInputPath: null, defaults: null, columnSettings: null, columnsTable: null, defaultsTable: null, init: function(columnsT...
(function($) {
random_line_split
TransposeCalculator.ts
import { ITransposeCalculator } from "../../MusicalScore/Interfaces"; import { Pitch, NoteEnum, AccidentalEnum } from "../../Common/DataObjects"; import { KeyInstruction } from "../../MusicalScore/VoiceData/Instructions"; /** Calculates transposition of individual notes and keys, * which is used by multiple OSMD clas...
}
{ let currentIndex: number = 0; let previousKeyType: number = 0; for (; currentIndex < TransposeCalculator.keyMapping.length; currentIndex++) { previousKeyType = TransposeCalculator.keyMapping[currentIndex]; if (previousKeyType === keyInstruction.keyTypeOriginal) { ...
identifier_body
TransposeCalculator.ts
import { ITransposeCalculator } from "../../MusicalScore/Interfaces"; import { Pitch, NoteEnum, AccidentalEnum } from "../../Common/DataObjects"; import { KeyInstruction } from "../../MusicalScore/VoiceData/Instructions"; /** Calculates transposition of individual notes and keys, * which is used by multiple OSMD clas...
(pitch: Pitch, currentKeyInstruction: KeyInstruction, halftones: number): Pitch { let transposedFundamentalNote: NoteEnum = NoteEnum.C; let transposedOctave: number = 0; let transposedAccidental: AccidentalEnum = AccidentalEnum.NONE; const result: { halftone: number, overflow: number } ...
transposePitch
identifier_name
TransposeCalculator.ts
import { ITransposeCalculator } from "../../MusicalScore/Interfaces"; import { Pitch, NoteEnum, AccidentalEnum } from "../../Common/DataObjects"; import { KeyInstruction } from "../../MusicalScore/VoiceData/Instructions"; /** Calculates transposition of individual notes and keys, * which is used by multiple OSMD clas...
let newIndex: number = (currentIndex + transpose); while (newIndex >= 12) { newIndex -= 12; } while (newIndex < 0) { newIndex += 12; } keyInstruction.Key = TransposeCalculator.keyMapping[newIndex]; keyInstruction.isTransposedBy = transpose...
{ previousKeyType = TransposeCalculator.keyMapping[currentIndex]; if (previousKeyType === keyInstruction.keyTypeOriginal) { break; } }
conditional_block
TransposeCalculator.ts
import { ITransposeCalculator } from "../../MusicalScore/Interfaces"; import { Pitch, NoteEnum, AccidentalEnum } from "../../Common/DataObjects"; import { KeyInstruction } from "../../MusicalScore/VoiceData/Instructions"; /** Calculates transposition of individual notes and keys, * which is used by multiple OSMD clas...
noteIndex += 7; transposedHalfTone += 12; octaveChange--; } while (noteIndex >= 7) { noteIndex -= 7; transposedHalfTone -= 12; octaveChange++; } ...
noteIndex--; } while (noteIndex < 0) {
random_line_split
threejs_coordinator.ts
/* Copyright 2020 The TensorFlow Authors. 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 applicable law or a...
extends Coordinator { override isYAxisPointedDown() { return false; } private readonly camera = new THREE.OrthographicCamera( 0, 1000, 1000, 0, 0, 100 ); override setDomContainerRect(rect: Rect) { // We set the camera extent based on the dom container size so the dimensions ...
ThreeCoordinator
identifier_name
threejs_coordinator.ts
/* Copyright 2020 The TensorFlow Authors. 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 applicable law or a...
* In this coordinator, the output coordinate system is static from [0, 1000]. */ export class ThreeCoordinator extends Coordinator { override isYAxisPointedDown() { return false; } private readonly camera = new THREE.OrthographicCamera( 0, 1000, 1000, 0, 0, 100 ); override setD...
random_line_split
answer.tsx
import React from "react"; import { getAnswersByQuestion } from "../../selectors/report-tree"; import { connect } from "react-redux"; import { AnswerProps } from "../../util/answer-utils"; import { getQuestionIcon } from "../../util/question-utils"; import MultipleChoiceAnswer from "../../components/portal-dashboard/mu...
extends React.PureComponent<AnswerProps> { constructor(props: AnswerProps) { super(props); } render() { const { answer, question, student } = this.props; const atype = answer && answer.get("type"); const QuestionIcon = getQuestionIcon(question); const key = `student-${student ? student.get("...
Answer
identifier_name
answer.tsx
import React from "react"; import { getAnswersByQuestion } from "../../selectors/report-tree"; import { connect } from "react-redux"; import { AnswerProps } from "../../util/answer-utils"; import { getQuestionIcon } from "../../util/question-utils"; import MultipleChoiceAnswer from "../../components/portal-dashboard/mu...
export default connect(mapStateToProps, mapDispatchToProps)(Answer);
const mapDispatchToProps = (dispatch: any, ownProps: any): Partial<AnswerProps> => { return {}; };
random_line_split
answer.tsx
import React from "react"; import { getAnswersByQuestion } from "../../selectors/report-tree"; import { connect } from "react-redux"; import { AnswerProps } from "../../util/answer-utils"; import { getQuestionIcon } from "../../util/question-utils"; import MultipleChoiceAnswer from "../../components/portal-dashboard/mu...
} } function mapStateToProps(state: any, ownProps: any): Partial<AnswerProps> { return { answer: getAnswersByQuestion(state) .getIn([ownProps.question.get("id"), ownProps.student.get("id")]) }; } const mapDispatchToProps = (dispatch: any, ownProps: any): Partial<AnswerProps> => { return {}; }; exp...
{ return ( <AComponent answer={answer} question={question} showFullAnswer={true} responsive={responsive} studentName={studentName} trackEvent={trackEvent} answerOrientation={answerOrientation} /> ); }
conditional_block
answer.tsx
import React from "react"; import { getAnswersByQuestion } from "../../selectors/report-tree"; import { connect } from "react-redux"; import { AnswerProps } from "../../util/answer-utils"; import { getQuestionIcon } from "../../util/question-utils"; import MultipleChoiceAnswer from "../../components/portal-dashboard/mu...
render() { const { answer, question, student } = this.props; const atype = answer && answer.get("type"); const QuestionIcon = getQuestionIcon(question); const key = `student-${student ? student.get("id") : "NA"}-question-${question ? question.get("id") : "NA"}`; return ( <div className={cs...
{ super(props); }
identifier_body
archives.js
"December"); var short_months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); if (full) { return full_months[num-1]; } return short_months[num-1]; } /* Returns the message list table header, including page selector and * sort links *...
if (msglist_http.status == 200) { /* 200 : OK */ _msglist = msglist_http.responseXML.documentElement; var i; drawFullMsgList (); /* Remove now useless loading message */ body.removeChild(document.getElementById('loading')); } } } msglist_http.open('GET', 'ajax/' + sort + '?' + page, true); ...
{ var msglist_http = getHTTPObject (); if (!msglist_http) { return false; } if (!sort) { sort = _sort; } if (!page) { page = _page; } _page = page; _sort = sort; /* The handler */ msglist_http.onreadystatechange = function () { if (msglist_http.readyState == 4) { /* 4 : "comple...
identifier_body
archives.js
("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); if (full) { return full_months[num-1]; } return short_months[num-1]; } /* Returns the message list table header, including page selector and * sort links */ function getMsgListHeader () { /* Fetch c...
str += '<tbody>'; str += '<tr class="from"><td class="left">From</td><td class="right">' +
random_line_split
archives.js
'<a href="browser" onclick="javascript:getMsgList(\'date\', null); return false;">Date</a>'; } else if (_sort == 'author') { str += '<a href="browser" onclick="javascript:getMsgList(\'thread\', null); return false;">Thread</a>' + ' &middot; Author &middot; ' + '<a href="browser" onclick="javas...
{ min = 0; }
conditional_block
archives.js
December"); var short_months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); if (full) { return full_months[num-1]; } return short_months[num-1]; } /* Returns the message list table header, including page selector and * sort links */ ...
(id, msg_num) { var str = '<tr><th class="title"><a href="' + id + '" title="Direct link to this message">Permalink (Message view)</a></th><th class="nav">'; if (msg_num) { str += '<a href="browser" onclick="javascript:toggleMessage(' + (msg_num-1) + '); return false;" title="View previous message">Previous...
getMessageView
identifier_name
Tileset.ts
import { ZeldaGame } from './ZeldaGame'; import { SpriteSheet } from 'gtp'; declare let game: ZeldaGame; /** * A set of tiles used by a map. */ export class Tileset { private _name: string; private _tiles: SpriteSheet; fromJson(json: TilesetData): Tileset { this.load(json.name); return t...
(): number { return this._tiles.size; } get name(): string { return this._name; } get rowCount(): number { return this._tiles.rowCount; } isDoorway(tile: number): boolean { if (this._name === 'overworld') { return tile === 61; // The single "door" t...
imageCount
identifier_name
Tileset.ts
import { ZeldaGame } from './ZeldaGame'; import { SpriteSheet } from 'gtp'; declare let game: ZeldaGame; /** * A set of tiles used by a map. */ export class Tileset { private _name: string; private _tiles: SpriteSheet; fromJson(json: TilesetData): Tileset { this.load(json.name); return t...
toJson(): TilesetData { return { name: this._name }; } } export interface TilesetData { name: string; }
{ this._tiles.drawByIndex(ctx, x, y, tile); }
identifier_body
Tileset.ts
import { ZeldaGame } from './ZeldaGame'; import { SpriteSheet } from 'gtp'; declare let game: ZeldaGame; /** * A set of tiles used by a map. */ export class Tileset { private _name: string; private _tiles: SpriteSheet; fromJson(json: TilesetData): Tileset { this.load(json.name); return t...
return false; } /** * Loads a tile set. * * @param name The name of the tileset. This should be the resource name, * as loaded by the game's resource loader. */ load(name: string) { this._name = name; this._tiles = game.assets.get(name); } ...
{ return tile === 61; // The single "door" tile }
conditional_block
Tileset.ts
import { ZeldaGame } from './ZeldaGame'; import { SpriteSheet } from 'gtp'; declare let game: ZeldaGame; /** * A set of tiles used by a map. */ export class Tileset { private _name: string; private _tiles: SpriteSheet; fromJson(json: TilesetData): Tileset { this.load(json.name); return t...
return this._name; } get rowCount(): number { return this._tiles.rowCount; } isDoorway(tile: number): boolean { if (this._name === 'overworld') { return tile === 61; // The single "door" tile } return false; } /** * Loads a tile set. ...
random_line_split
test_spin.py
# 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/. import pytest import math as m import numpy as np from sisl import Spin pytestmark = [pytest.mark.physics, pytest.ma...
import pickle as p S = Spin('nc') n = p.dumps(S) s = p.loads(n) assert S == s
identifier_body
test_spin.py
# 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/. import pytest import math as m import numpy as np from sisl import Spin pytestmark = [pytest.mark.physics, pytest.ma...
def test_spin2(): s1 = Spin() s2 = Spin('p') s3 = Spin('nc') s4 = Spin('so') assert s1.kind == Spin.UNPOLARIZED assert s2.kind == Spin.POLARIZED assert s3.kind == Spin.NONCOLINEAR assert s4.kind == Spin.SPINORBIT assert s1 == s1.copy() assert s2 == s2.copy() assert s3 ==...
s = Spin(val) str(s) s1 = s.copy() assert s == s1
conditional_block
test_spin.py
# 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/. import pytest import math as m import numpy as np from sisl import Spin pytestmark = [pytest.mark.physics, pytest.ma...
assert not s3.is_unpolarized assert not s3.is_polarized assert s3.is_noncolinear assert not s3.is_spinorbit assert not s4.is_unpolarized assert not s4.is_polarized assert not s4.is_noncolinear assert s4.is_spinorbit def test_spin3(): with pytest.raises(ValueError): s = Sp...
assert not s2.is_unpolarized assert s2.is_polarized assert not s2.is_noncolinear assert not s2.is_spinorbit
random_line_split
test_spin.py
# 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/. import pytest import math as m import numpy as np from sisl import Spin pytestmark = [pytest.mark.physics, pytest.ma...
(): s1 = Spin(Spin.UNPOLARIZED) S1 = Spin(Spin.UNPOLARIZED, np.complex64) s2 = Spin(Spin.POLARIZED) S2 = Spin(Spin.POLARIZED, np.complex64) s3 = Spin(Spin.NONCOLINEAR) S3 = Spin(Spin.NONCOLINEAR, np.complex64) s4 = Spin(Spin.SPINORBIT) S4 = Spin(Spin.SPINORBIT, np.complex64) assert s...
test_spin4
identifier_name
books.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), Book = mongoose.model('Book'), _ = require('lodash'); // , // googleapi = require('node-google-api')('AIzaSyAffzxPYpgZ14gieEE04_u4U-5Y26UQ8_0'); // exports.gbooks = function(req, res) { // goog...
else { res.jsonp(book); } }); }; /** * Show the current Book */ exports.read = function(req, res) { res.jsonp(req.book); }; /** * Update a Book */ exports.update = function(req, res) { var book = req.book ; book = _.extend(book , req.body); book.save(function(err) { if (err) { return res.status(...
{ return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); }
conditional_block
books.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), Book = mongoose.model('Book'), _ = require('lodash'); // , // googleapi = require('node-google-api')('AIzaSyAffzxPYpgZ14gieEE04_u4U-5Y26UQ8_0'); // exports.gbooks = function(req, res) { // goog...
res.jsonp(books); } }); }; /** * Book middleware */ exports.bookByID = function(req, res, next, id) { Book.findById(id).populate('user', 'displayName').exec(function(err, book) { if (err) return next(err); if (! book) return next(new Error('Failed to load Book ' + id)); req.book = book ; next(); }); }...
}); } else {
random_line_split
package.py
7', sha256='12389cf092dc032372617785822a597aee434a50a62db2a520ab35ba5a7548b5', url=baseurl + '/OpenFOAM-7/archive/version-7.tar.gz') version('6', sha256='32a6af4120e691ca2df29c5b9bd7bc7a3e11208947f9bccf6087cfff5492f025', url=baseurl + '/OpenFOAM-6/archive/version-6.tar.gz') version('5.0'...
(self, env, dependent_spec): """Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of previous versions. """ env.set('FOAM_PROJECT_DIR', self.projectdir) ...
setup_dependent_build_environment
identifier_name
package.py
_foam_arch = None # Content for etc/prefs.{csh,sh} etc_prefs = {} # Content for etc/config.{csh,sh}/ files etc_config = {} phases = ['configure', 'build', 'install'] build_script = './spack-Allwmake' # <- Added by patch() method. # # - End of definitions / setup - # # ...
dirs.extend(['doc'])
conditional_block
package.py
7', sha256='12389cf092dc032372617785822a597aee434a50a62db2a520ab35ba5a7548b5', url=baseurl + '/OpenFOAM-7/archive/version-7.tar.gz') version('6', sha256='32a6af4120e691ca2df29c5b9bd7bc7a3e11208947f9bccf6087cfff5492f025', url=baseurl + '/OpenFOAM-6/archive/version-6.tar.gz') version('5.0'...
def rename_source(self): """This is fairly horrible. The github tarfiles have weird names that do not correspond to the canonical name. We need to rename these, but leave a symlink for spack to work with. """ # Note that this particular OpenFOAM requires absolute di...
"""Relative location of architecture-specific libraries""" return join_path('platforms', self.foam_arch, 'lib')
identifier_body
package.py
('7', sha256='12389cf092dc032372617785822a597aee434a50a62db2a520ab35ba5a7548b5', url=baseurl + '/OpenFOAM-7/archive/version-7.tar.gz') version('6', sha256='32a6af4120e691ca2df29c5b9bd7bc7a3e11208947f9bccf6087cfff5492f025', url=baseurl + '/OpenFOAM-6/archive/version-6.tar.gz') version('5....
tty.warn(msg.format(str(e))) def setup_dependent_build_environment(self, env, dependent_spec): """Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of prev...
bashrc, clean=True )) except Exception as e: msg = 'unexpected error when sourcing OpenFOAM bashrc [{0}]'
random_line_split
dom.rs
( &self, _id: &Atom, ) -> Result<&[<Self::ConcreteNode as TNode>::ConcreteElement], ()> { Err(()) } } /// The `TNode` trait. This is the main generic trait over which the style /// system can be implemented. pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo + PartialEq { ///...
elements_with_id
identifier_name
dom.rs
self) -> bool; /// Flags this element as having handled already its snapshot. unsafe fn set_handled_snapshot(&self); /// Returns whether the element's styles are up-to-date for |traversal_flags|. fn has_current_styles_for_traversal( &self, data: &ElementData, traversal_flags: T...
{ *self }
conditional_block
dom.rs
impl<N> Iterator for DomDescendants<N> where N: TNode { type Item = N; #[inline] fn next(&mut self) -> Option<N> { let prev = match self.previous.take() { None => return None, Some(n) => n, }; self.previous = prev.next_in_preorder(Some(self.scope)); ...
}
random_line_split