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
hw5_start.py
# CIS 410/510pm # Homework 5 beta 0.0.1 # Cameron Palk # May 2016 # # Special thanks to Daniel Lowd for the skeletor code import sys import tokenize from functools import reduce global_card = [] num_vars = 0 ''' Calc Strides ''' def calcStrides( scope ): rev_scope = list( reversed( scope ) ) res = [ 1 ] + [ 0 ] *...
# Print results print( "Z =", z ) return # Run main if this module is being run directly if __name__ == '__main__': main()
# Computer partition function z = computePartitionFunction( factors )
random_line_split
hw5_start.py
# CIS 410/510pm # Homework 5 beta 0.0.1 # Cameron Palk # May 2016 # # Special thanks to Daniel Lowd for the skeletor code import sys import tokenize from functools import reduce global_card = [] num_vars = 0 ''' Calc Strides ''' def calcStrides( scope ): rev_scope = list( reversed( scope ) ) res = [ 1 ] + [ 0 ] *...
main()
conditional_block
hw5_start.py
# CIS 410/510pm # Homework 5 beta 0.0.1 # Cameron Palk # May 2016 # # Special thanks to Daniel Lowd for the skeletor code import sys import tokenize from functools import reduce global_card = [] num_vars = 0 ''' Calc Strides ''' def calcStrides( scope ): rev_scope = list( reversed( scope ) ) res = [ 1 ] + [ 0 ] *...
# def next_float(): return float( next_token() ) # def read_model(): # Read in all tokens and throw away the first (expected to be "MARKOV") read_tokens() s = next_token() # Get number of vars, followed by their ranges global num_vars num_vars = next_int() global global_card global_card = [ next_int() for ...
return int( next_token() )
identifier_body
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
/// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [ '{' as libc::c_char, '0' as libc::c_char, '}' as libc::c_char, 0 as libc::c_char, ]; /// Format string struct used to throw `TypeError`s. static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatStrin...
{ debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); }
identifier_body
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); } /// Format string used to throw javascript errors. static ERROR_FORMAT_STRING_STRING: [libc:...
random_line_split
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
, Error::Range(message) => { assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_range_error(cx, &message); return; }, Error::JSFailed => { assert!(unsafe { JS_IsExceptionPending(cx) } == 1); return; } }; assert!(...
{ assert!(unsafe { JS_IsExceptionPending(cx) } == 0); throw_type_error(cx, &message); return; }
conditional_block
error.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/. */ //! Utilities to throw exceptions from Rust bindings. use dom::bindings::codegen::PrototypeList::proto_id_to_name...
{ /// IndexSizeError DOMException IndexSize, /// NotFoundError DOMException NotFound, /// HierarchyRequestError DOMException HierarchyRequest, /// WrongDocumentError DOMException WrongDocument, /// InvalidCharacterError DOMException InvalidCharacter, /// NotSupportedError DO...
Error
identifier_name
webpack.config.prod.js
var path = require('path') var webpack = require('webpack') var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { vendor: ['react','redux','react-redux','react-router'], bundle: './src/index' }, output: { pa...
], module: { loaders: [{ test: /\.js$/, loaders: [ 'babel' ], exclude: /node_modules/, include: path.join(__dirname,'src') }, { test: /\.(css|scss)$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!sass-loader?sourceMap&includePaths[]=' + path.resolve(__...
minify:{ //压缩HTML文件 removeComments:false, //移除HTML中的注释 collapseWhitespace:true //删除空白符与换行符 } }),
random_line_split
__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 MicroEra s.r.l. # (<http://www.microera.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License...
'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
random_line_split
canalc.py
# -*- coding: utf-8 -*- # Copyright: (c) 2019, SylvainCecchetto # GNU General Public License v2.0+ (see LICENSE.txt or https://www.gnu.org/licenses/gpl-2.0.txt) # This file is part of Catch-up TV & More from __future__ import unicode_literals import re try: # Python 3 from urllib.parse import unquote_plus except...
(plugin, item_id, program_url, page, **kwargs): if page == '1': resp = urlquick.get(program_url) else: resp = urlquick.get(program_url + 'page/%s/' % page) root = resp.parse() for video_datas in root.iterfind(".//article"): if video_datas.find(".//h2") is not None: ...
list_videos
identifier_name
canalc.py
# -*- coding: utf-8 -*- # Copyright: (c) 2019, SylvainCecchetto # GNU General Public License v2.0+ (see LICENSE.txt or https://www.gnu.org/licenses/gpl-2.0.txt) # This file is part of Catch-up TV & More from __future__ import unicode_literals import re try: # Python 3 from urllib.parse import unquote_plus except...
stream_url = re.compile( r'source src\=\"(.*?)\"').findall(resp.text)[0] if download_mode: return download.download_video(stream_url) return stream_url video_id = re.compile(r'www.youtube.com\/embed\/(.*?)\"').findall(resp.text)[0] return resolver_proxy.get_stre...
if len(re.compile(r'source src\=\"(.*?)\"').findall(resp.text)) > 0:
random_line_split
canalc.py
# -*- coding: utf-8 -*- # Copyright: (c) 2019, SylvainCecchetto # GNU General Public License v2.0+ (see LICENSE.txt or https://www.gnu.org/licenses/gpl-2.0.txt) # This file is part of Catch-up TV & More from __future__ import unicode_literals import re try: # Python 3 from urllib.parse import unquote_plus except...
return stream_url video_id = re.compile(r'www.youtube.com\/embed\/(.*?)\"').findall(resp.text)[0] return resolver_proxy.get_stream_youtube(plugin, video_id, download_mode) @Resolver.register def get_live_url(plugin, item_id, **kwargs): resp = urlquick.get(URL_LIVE, max_age=-1) return unquot...
return download.download_video(stream_url)
conditional_block
canalc.py
# -*- coding: utf-8 -*- # Copyright: (c) 2019, SylvainCecchetto # GNU General Public License v2.0+ (see LICENSE.txt or https://www.gnu.org/licenses/gpl-2.0.txt) # This file is part of Catch-up TV & More from __future__ import unicode_literals import re try: # Python 3 from urllib.parse import unquote_plus except...
@Resolver.register def get_live_url(plugin, item_id, **kwargs): resp = urlquick.get(URL_LIVE, max_age=-1) return unquote_plus(re.compile(r'sourceURL\"\:\"(.*?)\"').findall(resp.text)[0])
resp = urlquick.get(video_url) if len(re.compile(r'source src\=\"(.*?)\"').findall(resp.text)) > 0: stream_url = re.compile( r'source src\=\"(.*?)\"').findall(resp.text)[0] if download_mode: return download.download_video(stream_url) return stream_url video_id ...
identifier_body
reset_zabbix_hosts.py
#!/usr/bin/python from pyzabbix import ZabbixAPI import sys username="wentian" password="65107318" zapi = ZabbixAPI("http://zabbix.ustack.com") zapi.login(username, password) print "Connected To Zabbix API Version %s" % zapi.api_version() hostgroup_id = sys.argv[1] status = int(sys.argv[2]) def get_hostgroup_id(h...
if __name__ == "__main__": hosts = get_hosts(get_hostgroup_id(hostgroup_id)) update_machine_set_status(hosts, status)
result_hosts = [] for host in hosts: result_hosts.append({"hostid": host["hostid"]}) zapi.host.massupdate(hosts=result_hosts, status=status)
identifier_body
reset_zabbix_hosts.py
#!/usr/bin/python from pyzabbix import ZabbixAPI import sys username="wentian" password="65107318" zapi = ZabbixAPI("http://zabbix.ustack.com") zapi.login(username, password) print "Connected To Zabbix API Version %s" % zapi.api_version() hostgroup_id = sys.argv[1] status = int(sys.argv[2]) def
(hostgroup_name): search = {"name": hostgroup_name} hostgroups = zapi.hostgroup.get(search=search) if len(hostgroups) > 0: return hostgroups[0]['groupid'] def get_hosts(groupid): groupids = [groupid] hosts = zapi.host.get(groupids=groupids) return hosts def update_machine_set_status(ho...
get_hostgroup_id
identifier_name
reset_zabbix_hosts.py
#!/usr/bin/python from pyzabbix import ZabbixAPI import sys username="wentian" password="65107318" zapi = ZabbixAPI("http://zabbix.ustack.com") zapi.login(username, password) print "Connected To Zabbix API Version %s" % zapi.api_version() hostgroup_id = sys.argv[1] status = int(sys.argv[2]) def get_hostgroup_id(h...
def get_hosts(groupid): groupids = [groupid] hosts = zapi.host.get(groupids=groupids) return hosts def update_machine_set_status(hosts, status=0): result_hosts = [] for host in hosts: result_hosts.append({"hostid": host["hostid"]}) zapi.host.massupdate(hosts=result_hosts, status=statu...
return hostgroups[0]['groupid']
conditional_block
reset_zabbix_hosts.py
#!/usr/bin/python from pyzabbix import ZabbixAPI import sys username="wentian" password="65107318" zapi = ZabbixAPI("http://zabbix.ustack.com") zapi.login(username, password) print "Connected To Zabbix API Version %s" % zapi.api_version() hostgroup_id = sys.argv[1] status = int(sys.argv[2])
def get_hostgroup_id(hostgroup_name): search = {"name": hostgroup_name} hostgroups = zapi.hostgroup.get(search=search) if len(hostgroups) > 0: return hostgroups[0]['groupid'] def get_hosts(groupid): groupids = [groupid] hosts = zapi.host.get(groupids=groupids) return hosts def update...
random_line_split
test_notes.py
""" Test diapason notes. """ import pytest from pytest import approx from diapason import note_frequency @pytest.mark.parametrize(('note', 'sharp', 'flat', 'octave', 'frequency'), [ # Exact frequencies (A) ('A', 0, 0, 4, 440.), ('A', 0, 0, 0, 27.5), ('A', 0, 0, 6, 1760.), # Different notes in the...
@pytest.mark.parametrize(('note', 'sharp', 'flat', 'octave', 'frequency'), [ # Exact frequencies (C) ('C', 0, 0, 0, 16.), ('C', 0, 0, 2, 64.), ('C', 0, 0, 4, 256.), ('C', 0, 0, 6, 1024.), ('C', 0, 0, 8, 4096.), # Other frequencies ('A', 0, 0, 4, 430.539), ]) def test_note_frequency_sc...
""" Basic note_frequency() function tests. """ actual = note_frequency(note, sharp=sharp, flat=flat, octave=octave) assert actual == approx(frequency, rel=1e-5)
identifier_body
test_notes.py
""" Test diapason notes. """ import pytest from pytest import approx from diapason import note_frequency @pytest.mark.parametrize(('note', 'sharp', 'flat', 'octave', 'frequency'), [ # Exact frequencies (A) ('A', 0, 0, 4, 440.), ('A', 0, 0, 0, 27.5), ('A', 0, 0, 6, 1760.), # Different notes in the...
with pytest.raises(ValueError): note_frequency(note, sharp, flat, octave)
Test note_frequency() ValueError exceptions. """
random_line_split
test_notes.py
""" Test diapason notes. """ import pytest from pytest import approx from diapason import note_frequency @pytest.mark.parametrize(('note', 'sharp', 'flat', 'octave', 'frequency'), [ # Exact frequencies (A) ('A', 0, 0, 4, 440.), ('A', 0, 0, 0, 27.5), ('A', 0, 0, 6, 1760.), # Different notes in the...
(note, sharp, flat, octave): """ Test note_frequency() ValueError exceptions. """ with pytest.raises(ValueError): note_frequency(note, sharp, flat, octave)
test_note_frequency_value_errors
identifier_name
ids.ts
import { Node } from 'prosemirror-model'; import { EditorState, Plugin, Transaction } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { generateHash } from '../utils'; const inPasteRange = (offset, transactions) => { return transactions.some((trans) => { const [step] = trans.steps; ...
} else if (nodeTypeHasId) { // If it doesn't have an ID, assign one as long as its // schema supports ID fields. mustReturnTransaction = true; transaction.setNodeMarkup(pos, node.type, updatedNodeAttrsWithNewRandomId(node)); } }); return mustReturnTransaction ? transaction : null; }; export default...
{ seenIds.add(node.attrs.id); if (possibleChangesForPastedNodes[node.attrs.id]) { const newChange = possibleChangesForPastedNodes[node.attrs.id]; mustReturnTransaction = true; transaction.setNodeMarkup(newChange.offset, newChange.type, newChange.attrs); } }
conditional_block
ids.ts
import { Node } from 'prosemirror-model'; import { EditorState, Plugin, Transaction } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { generateHash } from '../utils'; const inPasteRange = (offset, transactions) => { return transactions.some((trans) => { const [step] = trans.steps; ...
}, appendTransaction: (transactions, __, newState) => getIdsTransactionForState(newState, transactions), }); };
random_line_split
zfsmond.js
var app = angular.module('zfsmond', ['ui.bootstrap', 'ui.router','ngResource', 'zfsmond.pools','zfsmond.filesystems', 'zfsmond.disks', 'zfsmond.stats']); app.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/pools") $stateProvider.state('pools', { url: "/pools", templateUrl: "...
controller: 'DisksController as diskCtrl' }); $stateProvider.state('stats', { url: "/stats", templateUrl: "static/tabs/stats.html", controller: 'StatsController as statsCtrl' }); }); app.filter('bytes', function() { return function(bytes, precision) { if (bytes == 0) return 0; if (isNaN(parseFloat(byt...
templateUrl: "static/tabs/disks.html",
random_line_split
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
(&mut self, ptr: usize) -> Result<(), Error> { if ptr < self.pos_map.len() { self.ptr = Some(ptr); return Ok(()); } Err(Error::new( format!("FAULT!!! Invalid Jump!"), match self.pos() { Some(pos) => pos.clone(), None...
jump
identifier_name
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
)) } pub fn op(&self) -> Option<&Op> { if let Some(i) = self.ptr { return self.pos_map.ops.get(i); } None } pub fn pos(&self) -> Option<&Position> { if let Some(i) = self.ptr { return self.pos_map.pos.get(i); } None } ...
match self.pos() { Some(pos) => pos.clone(), None => Position::new(0, 0, 0), },
random_line_split
pointer.rs
// Copyright 2019 Jeremy Wall // // 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 ...
pub fn op(&self) -> Option<&Op> { if let Some(i) = self.ptr { return self.pos_map.ops.get(i); } None } pub fn pos(&self) -> Option<&Position> { if let Some(i) = self.ptr { return self.pos_map.pos.get(i); } None } pub fn idx(...
{ if ptr < self.pos_map.len() { self.ptr = Some(ptr); return Ok(()); } Err(Error::new( format!("FAULT!!! Invalid Jump!"), match self.pos() { Some(pos) => pos.clone(), None => Position::new(0, 0, 0), }, ...
identifier_body
parse_response_file.py
from ggrade import read_tab_file import argparse ################################################################################ ################################################################################ def main(): # Parse the input arguments
################################################################################ ################################################################################ if __name__=="__main__": main()
parser = argparse.ArgumentParser() parser.add_argument('infile_name', type=str, default=None, help='Input file name',nargs='?') parser.add_argument('--solutions-file', dest='outfile_name', type=str,\ default=None, help='Name of output file to write the solutions to.') args = parser.parse_args()...
identifier_body
parse_response_file.py
from ggrade import read_tab_file import argparse ################################################################################ ################################################################################ def main(): # Parse the input arguments parser = argparse.ArgumentParser() parser.add_argument...
if __name__=="__main__": main()
random_line_split
parse_response_file.py
from ggrade import read_tab_file import argparse ################################################################################ ################################################################################ def
(): # Parse the input arguments parser = argparse.ArgumentParser() parser.add_argument('infile_name', type=str, default=None, help='Input file name',nargs='?') parser.add_argument('--solutions-file', dest='outfile_name', type=str,\ default=None, help='Name of output file to write the soluti...
main
identifier_name
parse_response_file.py
from ggrade import read_tab_file import argparse ################################################################################ ################################################################################ def main(): # Parse the input arguments parser = argparse.ArgumentParser() parser.add_argument...
else: outfile_name = args.infile_name.split('.tsv')[0] outfile_name = "SOLUTIONS_%s.py" % (outfile_name) outfile = open(outfile_name,'w+') outfile.write("# -*- coding: utf-8 -*-") outfile.write("\n") outfile.write(solutions_string) outfile.write("\n") outfile.write(extra_f...
outfile_name = args.outfile_name
conditional_block
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
pub fn actions(mut self, actions: Vec<ActionType>) -> ContextConfigBuilder { self.actions = actions; self } pub fn name(mut self, name: String) -> ContextConfigBuilder { self.name = Some(name); self } pub fn patterns(mut self, patterns: Vec<String>) -> ContextConf...
{ self.context_id = context_id; self }
identifier_body
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
name: Option<String>, uuid: Uuid, conditions: Conditions, context_id: Option<Vec<String>>, actions: Vec<ActionType>, patterns: Vec<String> } impl ContextConfigBuilder { pub fn new(uuid: Uuid, conditions: Conditions) -> ContextConfigBuilder { ContextConfigBuilder { name: ...
pub struct ContextConfigBuilder {
random_line_split
mod.rs
// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com> // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not...
(mut self, patterns: Vec<String>) -> ContextConfigBuilder { self.patterns = patterns; self } pub fn build(self) -> ContextConfig { ContextConfig { name: self.name, uuid: self.uuid, conditions: self.conditions, context_id: self.context_id, ...
patterns
identifier_name
project.js
'use strict'; angular.module('sfchecks.project', ['ui.bootstrap', 'sgw.ui.breadcrumb', 'bellows.services', 'sfchecks.services', 'palaso.ui.listview', 'palaso.ui.typeahead', 'palaso.ui.notice', 'palaso.ui.textdrop', 'palaso.ui.jqte', 'ngFileUpload', 'ngRoute']) .controller('ProjectCtrl', ['$scope', 'textService',...
} }; // Listview Selection $scope.newTextCollapsed = true; $scope.selected = []; $scope.updateSelection = function (event, item) { var selectedIndex = $scope.selected.indexOf(item); var checkbox = event.target; if (checkbox.checked && selectedIndex == -1) { $scope.s...
{ $scope.messages.splice(i, 1); messageService.markRead(id); break; }
conditional_block
project.js
'use strict'; angular.module('sfchecks.project', ['ui.bootstrap', 'sgw.ui.breadcrumb', 'bellows.services', 'sfchecks.services', 'palaso.ui.listview', 'palaso.ui.typeahead', 'palaso.ui.notice', 'palaso.ui.textdrop', 'palaso.ui.jqte', 'ngFileUpload', 'ngRoute']) .controller('ProjectCtrl', ['$scope', 'textService',...
// Archive Texts $scope.archiveTexts = function () { //console.log("archiveTexts()"); var textIds = []; var message = ''; for (var i = 0, l = $scope.selected.length; i < l; i++) { textIds.push($scope.selected[i].id); } if (textIds.length == 1) { message = 'A...
$scope.finishedLoading = true; } }); };
random_line_split
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*;
/// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R2CPlan64, c2r: C2RPlan64, } impl Pair { pub fn new(n: usize) -> Self { let nf = n / 2 + 1; let mut r = AlignedVec::new(n); let mut c = AlignedVec::...
use fftw::plan::*; use fftw::types::*; use ndarray::*;
random_line_split
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*; use fftw::plan::*; use fftw::types::*; use ndarray::*; /// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R...
pub fn real_view_mut(&mut self) -> ArrayViewMut1<f64> { ArrayViewMut::from_shape(self.r.len(), &mut self.r).unwrap() } pub fn coeff_view_mut(&mut self) -> ArrayViewMut1<c64> { ArrayViewMut::from_shape(self.c.len(), &mut self.c).unwrap() } } impl Clone for Pair { fn clone(&self) -...
{ ArrayView::from_shape(self.c.len(), &self.c).unwrap() }
identifier_body
mod.rs
//! Example nonlinear PDEs pub mod kse; pub mod she; pub use self::kse::KSE; pub use self::she::SWE; use fftw::array::*; use fftw::plan::*; use fftw::types::*; use ndarray::*; /// Pair of one-dimensional Real/Complex aligned arrays pub struct Pair { pub r: AlignedVec<f64>, pub c: AlignedVec<c64>, r2c: R...
(&mut self) { self.r2c.r2c(&mut self.r, &mut self.c).unwrap(); let n = 1.0 / self.r.len() as f64; for v in self.c.iter_mut() { *v *= n; } } pub fn c2r(&mut self) { self.c2r.c2r(&mut self.c, &mut self.r).unwrap(); } pub fn to_r<'a, 'b>(&'a mut self, c:...
r2c
identifier_name
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn
(args: Args, context: Context) { thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visualizations_dir.read_dir() { Ok(read_dir) => { for dir_entry_result in read_dir { match ...
start
identifier_name
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn start(args: Args, context: Context)
{ thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visualizations_dir.read_dir() { Ok(read_dir) => { for dir_entry_result in read_dir { match dir_entry_result { ...
identifier_body
renderer.rs
use log::{debug, error}; use std::{thread, time::Duration}; use crate::args::Args; use crate::context::Context; use crate::process; pub fn start(args: Args, context: Context) { thread::spawn(move || { let visualizations_dir = context.data_dir.join("visualizations"); loop { match visua...
debug!("The blender child process finished"); } else { let blender_output = process::debug_output(output); error!("The blender child process returned an error exit ...
Ok(output) => if output.status.success() {
random_line_split
import.py
import sys, getopt import os.path import sqlite3, json import requests import config # config file from scrapinghub import Connection """ Scrapinghub2Sqlite 1. Create sqlite database (if not exists yet, obviously) a. Create tables 2. get all projects from scrapinghub 3. check for new projects (not stored yet in lo...
(argv): getDeleted = False opts, args = getopt.getopt(argv, "d", ["deleted"]) for opt, arg in opts: if opt in ("-d", "--deleted"): getDeleted = True # create schema if db not exists if not os.path.isfile(config.database): createSchema = True else: createSchema = False connection = Connection(config....
main
identifier_name
import.py
import sys, getopt import os.path import sqlite3, json import requests import config # config file from scrapinghub import Connection """ Scrapinghub2Sqlite 1. Create sqlite database (if not exists yet, obviously) a. Create tables 2. get all projects from scrapinghub 3. check for new projects (not stored yet in lo...
db.commit() # get projects project_ids = connection.project_ids() for project_id in project_ids: project = connection[project_id] cursor.execute('''SELECT * FROM shub_projects WHERE shub_id = ?''', (project.id,)) # insert if not exist if len(cursor.fetchall()) == 0: print "Guardando proyect...
cursor.execute(line)
conditional_block
import.py
import sys, getopt import os.path import sqlite3, json import requests import config # config file from scrapinghub import Connection """ Scrapinghub2Sqlite 1. Create sqlite database (if not exists yet, obviously) a. Create tables 2. get all projects from scrapinghub 3. check for new projects (not stored yet in lo...
project = connection[project_id] cursor.execute('''SELECT * FROM shub_projects WHERE shub_id = ?''', (project.id,)) # insert if not exist if len(cursor.fetchall()) == 0: print "Guardando proyecto " + str(project.id) + "..." db.execute('''INSERT INTO shub_projects (shub_id) VALUES (?)''',\...
for project_id in project_ids:
random_line_split
import.py
import sys, getopt import os.path import sqlite3, json import requests import config # config file from scrapinghub import Connection """ Scrapinghub2Sqlite 1. Create sqlite database (if not exists yet, obviously) a. Create tables 2. get all projects from scrapinghub 3. check for new projects (not stored yet in lo...
def getJobs(db, jobs): for job in jobs: cursor = db.cursor() cursor.execute('''SELECT * FROM shub_jobs WHERE shub_id = ?''',\ (job.id,)) # insert jobs if not exists if len(cursor.fetchall()) == 0: print "Guardando job " + job.id + "..." jsonString = json.dumps(job.info) db.exe...
url = 'https://storage.scrapinghub.com/items/' + job_id \ + '?format=json&meta=_key&meta=_ts&apikey=' + config.apikey print url res = requests.get(url) return res.json()
identifier_body
popup.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Popup windows //>>label: Popups //>>group: Widgets //>>css.theme: ../css/themes/default/jquery.mobile.theme.css //>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery...
if ( !infoOnly ) { // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rectangle.cx ); } menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; return { rc: rectangle, menuSize: menuSize }; }, _calculateF...
y: windowCoordinates.y + this._tolerance.t, cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b };
random_line_split
popup.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Popup windows //>>label: Popups //>>group: Widgets //>>css.theme: ../css/themes/default/jquery.mobile.theme.css //>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery...
( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, overlayTheme: null, shadow: true...
getWindowCoordinates
identifier_name
popup.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Popup windows //>>label: Popups //>>group: Widgets //>>css.theme: ../css/themes/default/jquery.mobile.theme.css //>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery...
function getWindowCoordinates( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, ove...
{ var returnValue = desired; if ( windowSize < segmentSize ) { // Center segment if it's bigger than the window returnValue = offset + ( windowSize - segmentSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window returnValue = Math.min( Math.max( o...
identifier_body
popup.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Popup windows //>>label: Popups //>>group: Widgets //>>css.theme: ../css/themes/default/jquery.mobile.theme.css //>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery...
else { theEvent.preventDefault(); } } // remove nav bindings this.window.off( currentOptions.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents ); this._close( immediate ); }, // any na...
{ // Going to a different page - close immediately immediate = true; }
conditional_block
spaceWorldHighlighter.js
/* Custom syntax highlighter for SpaceWorld setting for brace * (which is used by react-ace editor). * Expects global ace variable to be present. * Usage: * ``` * import AceEditor from 'react-ace'; * import '../core/spaceWorldHighlighter'; * ... * <AceEditor mode="spaceworld" /> * ``` */ /* glob...
() { this.HighlightRules = HighlightRules; this.$behaviour = this.$defaultBehaviour; } oop.inherits(Mode, TextMode); (function setId() { this.$id = 'ace/mode/spaceworld'; }).call(Mode.prototype); exports.Mode = Mode; } );
Mode
identifier_name
spaceWorldHighlighter.js
/* Custom syntax highlighter for SpaceWorld setting for brace * (which is used by react-ace editor). * Expects global ace variable to be present. * Usage: * ``` * import AceEditor from 'react-ace'; * import '../core/spaceWorldHighlighter'; * ... * <AceEditor mode="spaceworld" /> * ``` */ /* glob...
oop.inherits(Mode, TextMode); (function setId() { this.$id = 'ace/mode/spaceworld'; }).call(Mode.prototype); exports.Mode = Mode; } );
{ this.HighlightRules = HighlightRules; this.$behaviour = this.$defaultBehaviour; }
identifier_body
spaceWorldHighlighter.js
/* Custom syntax highlighter for SpaceWorld setting for brace * (which is used by react-ace editor). * Expects global ace variable to be present. * Usage: * ``` * import AceEditor from 'react-ace'; * import '../core/spaceWorldHighlighter'; * ... * <AceEditor mode="spaceworld" /> * ``` */ /* glob...
regex: 'y', }, { token: colorTokens.black, regex: '(S|D|A|M|W)', }, { }, { token: colorTokens.gray, regex: '\\|', }, { token: colorTokens.gray, regex: '.', }, ], }; } ...
regex: 'm', }, { token: colorTokens.yellow,
random_line_split
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
use rustc_serialize::hex::ToHex; use serde; use util::{U256 as EthU256, Uint}; macro_rules! impl_uint { ($name: ident, $other: ident, $size: expr) => { /// Uint serialization. #[derive(Debug, Default, Clone, Copy, PartialEq, Hash)] pub struct $name($other); impl Eq for $name { } impl<T> From<T> for $name ...
use std::cmp; use std::str::FromStr;
random_line_split
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { let deserialized1: Res = serde_json::from_str(r#""""#); let deserialized2: Res = serde_json::from_str(r#""0""#); let deserialized3: Res = serde_json::from_str(r#""10""#); let deserialized4: Res = serde_json::from_str(r#""1000000""#); let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""...
should_fail_to_deserialize_decimals
identifier_name
uint.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
#[test] fn should_deserialize_u256() { let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap(); let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap(); let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap(); let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unw...
{ let deserialized1: Res = serde_json::from_str(r#""""#); let deserialized2: Res = serde_json::from_str(r#""0""#); let deserialized3: Res = serde_json::from_str(r#""10""#); let deserialized4: Res = serde_json::from_str(r#""1000000""#); let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);...
identifier_body
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
/// Handle configs like: /// /// ```toml /// format = "{layout}" /// ``` fn visit_str<E>(self, full: &str) -> StdResult<FormatTemplate, E> where E: de::Error, { FormatTemplate::new(full, Non...
{ formatter.write_str("format structure") }
identifier_body
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
() { let format = FormatTemplate::new("some text {foo} {bar:1} foobar", None); assert!(format.is_ok()); let format = format.unwrap(); assert!(format.contains("foo")); assert!(format.contains("bar")); assert!(!format.contains("foobar")); assert!(!format.contains("r...
contains
identifier_name
formatting.rs
pub mod placeholder; pub mod prefix; pub mod unit; pub mod value; use std::borrow::Borrow; use std::collections::HashMap; use std::fmt; use std::hash::Hash; use serde::de::{MapAccess, Visitor}; use serde::{de, Deserialize, Deserializer}; use crate::errors::*; use placeholder::unexpected_token; use placeholder::Place...
false } fn tokens_from_string(mut s: &str) -> Result<Vec<Token>> { let mut tokens = vec![]; // Push text into tokens vector. Check the text for correctness and don't push empty strings let push_text = |tokens: &mut Vec<Token>, x: &str| { if x.contains('{') { ...
} } } }
random_line_split
admin_flags_controller.js
/** This controller supports the interface for dealing with flags in the admin section. @class AdminFlagsController @extends Ember.Controller @namespace Discourse @module Discourse **/ Discourse.AdminFlagsController = Ember.ArrayController.extend({ /** Clear all flags on a post @method clearFlags...
var adminFlagsController = this; item.deletePost().then((function() { adminFlagsController.removeObject(item); }), function() { bootbox.alert(I18n.t("admin.flags.error")); }); }, /** Deletes a user and all posts and topics created by that user. @method deleteSpammer @param ...
random_line_split
analyzeBundle.py
#!/usr/bin/env python3 import os bundleFilesDir = 'tmp/bundleSizeDownloads' yarnLockFile = 'yarn.lock' packagesFile = 'package.json' def isDividerLine(line): # At least 80 chars, all slashes except the last (which is newline). The number is inconsistent for some reason.
def isSpacerLine(line): # At least 80 chars, starting with "//", ending with "//\n", otherwise all spaces return (len(line)>=80 and line.startswith("//") and line.endswith("//\n") and all([c==' ' for c in line[2:-3]])) assert isDividerLine("////////////////////////////////////////////////////...
return (len(line)>=80 and line.endswith("\n") and all([c=='/' for c in line[0:-1]]))
identifier_body
analyzeBundle.py
#!/usr/bin/env python3 import os bundleFilesDir = 'tmp/bundleSizeDownloads' yarnLockFile = 'yarn.lock' packagesFile = 'package.json' def isDividerLine(line): # At least 80 chars, all slashes except the last (which is newline). The number is inconsistent for some reason. return (len(line)>=80 and line....
return sizes def ancestorPaths(filename): pathComponents = filename.split('/') return ['.']+['/'.join(pathComponents[0:i]) for i in range(1,len(pathComponents))] def sumSizesInDirectories(sizesByFilename): sizesByDirectory = {} for filename in sizesByFilename: for path in ancestorPat...
fileContents = '\n'.join(lines[currentFileStart:i]) sizes[currentFileName] = len(fileContents)
conditional_block
analyzeBundle.py
#!/usr/bin/env python3 import os bundleFilesDir = 'tmp/bundleSizeDownloads' yarnLockFile = 'yarn.lock' packagesFile = 'package.json' def isDividerLine(line): # At least 80 chars, all slashes except the last (which is newline). The number is inconsistent for some reason. return (len(line)>=80 and line....
(lines): sizes = {} currentFileStart = None currentFileName = None for i in range(0,len(lines)): if i+4<len(lines) and isDividerLine(lines[i]) and isSpacerLine(lines[i+1]) and isSpacerLine(lines[i+3]) and isDividerLine(lines[i+4]): if currentFileName: fileContents = ...
unpackFile
identifier_name
analyzeBundle.py
#!/usr/bin/env python3
packagesFile = 'package.json' def isDividerLine(line): # At least 80 chars, all slashes except the last (which is newline). The number is inconsistent for some reason. return (len(line)>=80 and line.endswith("\n") and all([c=='/' for c in line[0:-1]])) def isSpacerLine(line): # At least 80...
import os bundleFilesDir = 'tmp/bundleSizeDownloads' yarnLockFile = 'yarn.lock'
random_line_split
onFileChange.js
/** * fs.watch wrapper that among other things checks SHA1 * of the file to prevent multiple callback calls. * * Related: http://stackoverflow.com/q/12978924/1637178 * * Usage is the same as fs.watch * * var onFileChange = require("on-file-change"); * * // same as fs.watch * onFileChange("m...
if(typeof callback === 'function') { if(init() === false) { throw new Error("Cannot initialize"); } return { "close": fileWatchers[path].close }; } else { ...
if(! fs.existsSync(path)) { console.error("Path "+path+" does not exists"); return false; } else { hashSums[path] || (hashSums[path] = getSha1FromFile(path)); // Try to prevent many eve...
identifier_body
onFileChange.js
/** * fs.watch wrapper that among other things checks SHA1 * of the file to prevent multiple callback calls. * * Related: http://stackoverflow.com/q/12978924/1637178 * * Usage is the same as fs.watch * * var onFileChange = require("on-file-change"); * * // same as fs.watch * onFileChange("m...
{ if(! fs.existsSync(path)) { console.error("Path "+path+" does not exists"); return false; } else { hashSums[path] || (hashSums[path] = getSha1FromFile(path)); // Try to prev...
it()
identifier_name
onFileChange.js
/** * fs.watch wrapper that among other things checks SHA1 * of the file to prevent multiple callback calls. * * Related: http://stackoverflow.com/q/12978924/1637178 * * Usage is the same as fs.watch * * var onFileChange = require("on-file-change"); * * // same as fs.watch * onFileChange("m...
return { "close": fileWatchers[path].close }; } else { throw new Error("No callback for onFileChange"); } } }());
throw new Error("Cannot initialize"); }
conditional_block
onFileChange.js
/** * fs.watch wrapper that among other things checks SHA1 * of the file to prevent multiple callback calls. * * Related: http://stackoverflow.com/q/12978924/1637178 * * Usage is the same as fs.watch * * var onFileChange = require("on-file-change"); * * // same as fs.watch * onFileChange("m...
}); } } if(typeof callback === 'function') { if(init() === false) { throw new Error("Cannot initialize"); } return { "close": fileWatchers[path].close }; ...
init(); }
random_line_split
ChampionPicker.js
import React from 'react'; import _ from 'lodash'; import staticApi from '../static/api'; import ChampionIcon from './ChampionIcon'; import Picker from './Picker'; import setChampion from '../actions/setChampion'; class ChampionPicker extends React.Component { constructor(props)
pickChampion(event, champion) { this.setState({visible: false, target: null}); this.context.executeAction(setChampion, {champion: champion}); } render() { if (!this.state.target) { return null; } let selected = this.state.champion; let otherChampions = _.without(staticApi.getCham...
{ super(props); this.state = {target: null, picked: null, visible: false}; this.pickChampion = this.pickChampion.bind(this); }
identifier_body
ChampionPicker.js
import React from 'react'; import _ from 'lodash'; import staticApi from '../static/api'; import ChampionIcon from './ChampionIcon'; import Picker from './Picker'; import setChampion from '../actions/setChampion'; class ChampionPicker extends React.Component { constructor(props) { super(props); this.state = ...
let selected = this.state.champion; let otherChampions = _.without(staticApi.getChampions(), selected); // Display selected first let champions = [selected].concat(otherChampions); let championIcons = champions.map((champion) => { return <ChampionIcon champion={champion} onClick={this.pick...
{ return null; }
conditional_block
ChampionPicker.js
import React from 'react'; import _ from 'lodash'; import staticApi from '../static/api'; import ChampionIcon from './ChampionIcon'; import Picker from './Picker'; import setChampion from '../actions/setChampion'; class ChampionPicker extends React.Component {
(props) { super(props); this.state = {target: null, picked: null, visible: false}; this.pickChampion = this.pickChampion.bind(this); } pickChampion(event, champion) { this.setState({visible: false, target: null}); this.context.executeAction(setChampion, {champion: champion}); } render() { ...
constructor
identifier_name
ChampionPicker.js
import React from 'react'; import _ from 'lodash'; import staticApi from '../static/api'; import ChampionIcon from './ChampionIcon'; import Picker from './Picker'; import setChampion from '../actions/setChampion'; class ChampionPicker extends React.Component { constructor(props) { super(props); this.state = ...
ChampionPicker.contextTypes = { executeAction: React.PropTypes.func.isRequired }; export default ChampionPicker;
</Picker>; } }
random_line_split
util.ts
import {NgZone} from '@angular/core'; import {Observable, OperatorFunction} from 'rxjs'; export function toInteger(value: any): number { return parseInt(`${value}`, 10); } export function toString(value: any): string { return (value !== undefined && value !== null) ? `${value}` : ''; } export function getValueIn...
return element.closest(selector); } /** * Force a browser reflow * @param element element where to apply the reflow */ export function reflow(element: HTMLElement) { return (element || document.body).getBoundingClientRect(); } /** * Creates an observable where all callbacks are executed inside a given zone ...
{ return null; }
conditional_block
util.ts
import {NgZone} from '@angular/core'; import {Observable, OperatorFunction} from 'rxjs'; export function toInteger(value: any): number { return parseInt(`${value}`, 10); } export function toString(value: any): string { return (value !== undefined && value !== null) ? `${value}` : ''; } export function getValueIn...
return str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); }
}; } export function removeAccents(str: string): string {
random_line_split
util.ts
import {NgZone} from '@angular/core'; import {Observable, OperatorFunction} from 'rxjs'; export function toInteger(value: any): number { return parseInt(`${value}`, 10); } export function toString(value: any): string { return (value !== undefined && value !== null) ? `${value}` : ''; } export function getValueIn...
export function hasClassName(element: any, className: string): boolean { return element && element.className && element.className.split && element.className.split(/\s+/).indexOf(className) >= 0; } if (typeof Element !== 'undefined' && !Element.prototype.closest) { // Polyfill for ie10+ Element.prototype....
{ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); }
identifier_body
util.ts
import {NgZone} from '@angular/core'; import {Observable, OperatorFunction} from 'rxjs'; export function toInteger(value: any): number { return parseInt(`${value}`, 10); } export function toString(value: any): string { return (value !== undefined && value !== null) ? `${value}` : ''; } export function getValueIn...
<T>(zone: NgZone): OperatorFunction<T, T> { return (source) => { return new Observable(observer => { const next = (value: T) => zone.run(() => observer.next(value)); const error = (e: any) => zone.run(() => observer.error(e)); const complete = () => zone.run(() => observer.complete()); ret...
runInZone
identifier_name
codeforces.js
CATS.Adapter.Codeforces = Classify({ init : function() { this.name = "codeforces"; this.contest_aliases = { id : 'id', name : 'name', startTimeSeconds : 'start_time', }, this.rules_aliases = { ICPC : 'acm' } }, parse_s...
row['user'] = user.id; var prob_num = 0; $.each(v.problemResults, function(k, v) { var prob = result_table.get_empty_problem_for_score_board_row(); prob['problem'] = problem_list[prob_num++]; prob['is_solved'] = v["bestSubmissionTimeSec...
var row = result_table.get_empty_score_board_row(); row['place'] = v.rank; row['penalty'] = v.penalty;
random_line_split
codeforces.js
CATS.Adapter.Codeforces = Classify({ init : function() { this.name = "codeforces"; this.contest_aliases = { id : 'id', name : 'name', startTimeSeconds : 'start_time', }, this.rules_aliases = { ICPC : 'acm' } }, parse_s...
prob['runs_cnt'] = v["rejectedAttemptCount"] + 1; row['problems'].push(prob); }); result_table.score_board.push(row); }); }, add_contest: function(v) { var contest = CATS.Model.Contest(); contest.id = v['id']; contest.na...
{ prob['best_run_time'] = Math.round(v["bestSubmissionTimeSeconds"] / 60); //we use minutes row['solved_cnt']++; }
conditional_block
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
Iterate(_) => unimplemented!() } } } for head_clause in rule.head.iter() { assert!(self.new_fact(&substitute(&head_clause, &ans)).is_ok()); } } } } SearchInvalid(s) => panic!("Internal invali...
{ //Definition should be next to be defined. assert!(n as usize == ans.len()); ans.push(rhs.clone()); }
conditional_block
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
pub fn reg_func(&mut self, name : String, func : HFunc) { self.funcs.insert(name, func); } }
} }
random_line_split
engine.rs
use fact_db::FactDB; use std::collections::hash_map::HashMap; use native_types::*; pub struct Engine { fact_db : Box<FactDB + Send>, funcs : HashMap<String, HFunc> } #[derive(Debug)] pub enum Error { Invalid(String), Internal(String), Type(String), Db(String) } use self::Error::*; fn substitute(clause ...
(&mut self, rule : &Rule) { use fact_db::SearchResponse::*; match self.fact_db.search_facts(&rule.body) { SearchAns(anss) => { //TODO: support anything other than one match, then wheres 'ans: for ans in anss { if self.fact_db.rule_cache_miss(&rule, &ans) { let mut ans...
run_rule
identifier_name
magfit_motors.py
#!/usr/bin/env python ''' fit best estimate of magnetometer offsets, trying to take into account motor interference ''' import sys, time, os, math from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log...
if m.get_type() == "RAW_IMU": mag = Vector3(m.xmag, m.ymag, m.zmag) # add data point after subtracting the current offsets data.append((mag - offsets + noise(), motor)) print("Extracted %u data points" % len(data)) print("Current offsets: %s" % offsets) data = ...
motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw motor_pwm *= 0.25 rc3_min = mlog.param('RC3_MIN', 1100) rc3_max = mlog.param('RC3_MAX', 1900) motor = (motor_pwm - rc3_min) / (rc3_max - rc3_min) if motor > 1.0: motor = 1.0 ...
conditional_block
magfit_motors.py
#!/usr/bin/env python ''' fit best estimate of magnetometer offsets, trying to take into account motor interference ''' import sys, time, os, math from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log...
(logfile): '''find best magnetometer offset fit to a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps) data = [] last_t = 0 offsets = Vector3(0,0,0) motor_ofs = Vector3(0,0,0) motor = 0.0 # now gather all...
magfit
identifier_name
magfit_motors.py
#!/usr/bin/env python ''' fit best estimate of magnetometer offsets, trying to take into account motor interference ''' import sys, time, os, math from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log...
from pymavlink import mavutil from pymavlink.rotmat import Vector3 def noise(): '''a noise vector''' from random import gauss v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1)) v.normalize() return v * args.noise def select_data(data): ret = [] counts = {} for d in data: (mag,...
args = parser.parse_args()
random_line_split
magfit_motors.py
#!/usr/bin/env python ''' fit best estimate of magnetometer offsets, trying to take into account motor interference ''' import sys, time, os, math from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log...
def sphere_error(p, data): from scipy import sqrt x,y,z,mx,my,mz,r = p ofs = Vector3(x,y,z) motor_ofs = Vector3(mx,my,mz) ret = [] for d in data: (mag,motor) = d err = r - radius((mag,motor), ofs, motor_ofs) ret.append(err) return ret def fit_data(data): import...
'''return radius give data point and offsets''' diff = radius(a, offsets, motor_ofs) - radius(b, offsets, motor_ofs) if diff > 0: return 1 if diff < 0: return -1 return 0
identifier_body
atom-linter.d.ts
// Type definitions for Atom Linter v2 // Project: https://github.com/steelbrain/linter // Type definitions for the few data structures referenced in the Linter // documentation found here: // http://steelbrain.me/linter/ declare module "atom-linter" { import { Disposable, Point, Range, TextEditor } from "atom"; ...
icon?: string; /** The text for the message. */ excerpt: string; /** The severity level for the message. */ severity: "error"|"warning"|"info"; /** Possible solutions (which the user can invoke at will). */ solutions?: Array<ReplacementSolution|CallbackSolution>; /** * Markdown ...
url?: string; /** The name of the octicon to show in the gutter. */
random_line_split
Timer.py
import collections from supriya.enums import CalculationRate from supriya.synthdefs import UGen class Timer(UGen): """ :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer Timer.ar() """ ### CLASS VARIABLES ### _ordered_input_na...
>>> timer.trigger 0.0 Returns ugen input. """ index = self._ordered_input_names.index('trigger') return self._inputs[index]
>>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... )
random_line_split
Timer.py
import collections from supriya.enums import CalculationRate from supriya.synthdefs import UGen class Timer(UGen): """ :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer Timer.ar() """ ### CLASS VARIABLES ### _ordered_input_na...
( cls, trigger=0, ): """ Constructs an audio-rate Timer. :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer Timer.ar() Returns ugen graph. """ import supriya....
ar
identifier_name
Timer.py
import collections from supriya.enums import CalculationRate from supriya.synthdefs import UGen class Timer(UGen): """ :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer Timer.ar() """ ### CLASS VARIABLES ### _ordered_input_na...
### PUBLIC PROPERTIES ### @property def trigger(self): """ Gets `trigger` input of Timer. :: >>> timer = supriya.ugens.Timer.ar( ... trigger=0, ... ) >>> timer.trigger 0.0 Returns ugen input. ""...
""" Constructs a control-rate Timer. :: >>> timer = supriya.ugens.Timer.kr( ... trigger=0, ... ) >>> timer Timer.kr() Returns ugen graph. """ import supriya.synthdefs calculation_rate = supriya.Calcula...
identifier_body
MeshLambertMaterial.js
/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: <hex>, * opacity: <float>, * * map: new THREE.Texture( <Image> ), * * lightMap: new THREE.Texture( <Image> ), * lightMapIntensity: <float> * * aoMap: new THREE.Texture( <Image> ), * ...
* * wireframe: <boolean>, * wireframeLinewidth: <float>, * * skinning: <bool>, * morphTargets: <bool>, * morphNormals: <bool> * } */ THREE.MeshLambertMaterial = function ( parameters ) { THREE.Material.call( this ); this.type = 'MeshLambertMaterial'; this.color = new THREE.Color( 0xffffff ); // dif...
* envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: <float>, * refractionRatio: <float>,
random_line_split
file_io.py
# Copyright 2015 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 applica...
file_list = get_matching_files(os.path.join(compat.as_str_any(dirname), "*")) return [ compat.as_str_any(pywrap_tensorflow.Basename(compat.as_bytes(filename))) for filename in file_list ] def walk(top, in_order=True): """Recursive directory tree generator for directories. Args: top: string...
raise errors.NotFoundError(None, None, "Could not find directory")
conditional_block
file_io.py
# Copyright 2015 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 applica...
(oldpath, newpath, overwrite=False): """Copies data from oldpath to newpath. Args: oldpath: string, name of the file who's contents need to be copied newpath: string, name of the file to which to copy to overwrite: boolean, if false its an error for newpath to be occupied by an existing file. ...
copy
identifier_name
file_io.py
# Copyright 2015 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 applica...
def readline(self): r"""Reads the next line from the file. Leaves the '\n' at the end.""" self._preread_check() return compat.as_str_any(self._read_buf.ReadLineAsString()) def readlines(self): """Returns all lines from the file in a list.""" self._preread_check() lines = [] while True:...
pywrap_tensorflow.Set_TF_Status_from_Status(status, ret_status)
random_line_split
file_io.py
# Copyright 2015 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 applica...
def rename(oldname, newname, overwrite=False): """Rename or move a file / directory. Args: oldname: string, pathname for a file newname: string, pathname to which the file needs to be moved overwrite: boolean, if false its an error for newpath to be occupied by an existing file. Raises: ...
"""Copies data from oldpath to newpath. Args: oldpath: string, name of the file who's contents need to be copied newpath: string, name of the file to which to copy to overwrite: boolean, if false its an error for newpath to be occupied by an existing file. Raises: errors.OpError: If the op...
identifier_body
base_module.py
from abc import ABCMeta from up.utils.up_logger import UpLogger class BaseModule(metaclass=ABCMeta): LOAD_ORDER = 0 def __init__(self, silent=False): self.__silent = silent self.__logger = UpLogger.get_logger() self.__up = None def initialize(self, up): self.__up = up ...
def load(self): return False def is_a(self, module_name): return self.__class__.__name__ == module_name @property def logger(self): return self.__logger @property def class_name(self): """ :rtype: str """ return self.__class__.__name_...
self.logger.critical(message)
conditional_block
base_module.py
from abc import ABCMeta from up.utils.up_logger import UpLogger class BaseModule(metaclass=ABCMeta): LOAD_ORDER = 0 def __init__(self, silent=False): self.__silent = silent self.__logger = UpLogger.get_logger() self.__up = None def initialize(self, up): self.__up = up ...
@classmethod def instance(cls, up): up.get_module(cls)
return None
identifier_body
base_module.py
from abc import ABCMeta from up.utils.up_logger import UpLogger class BaseModule(metaclass=ABCMeta): LOAD_ORDER = 0 def __init__(self, silent=False): self.__silent = silent self.__logger = UpLogger.get_logger() self.__up = None def initialize(self, up): self.__up = up ...
(self): """ Subclasses must override this method. Initialize the provider here. :return: None """ pass def _log_debug(self, message): if not self.__silent: self.logger.debug(message) def _log_info(self, message): if not self.__silent: ...
_execute_initialization
identifier_name
base_module.py
from abc import ABCMeta from up.utils.up_logger import UpLogger
def __init__(self, silent=False): self.__silent = silent self.__logger = UpLogger.get_logger() self.__up = None def initialize(self, up): self.__up = up self._log_debug("Initializing {}".format(self.class_name)) self._execute_initialization() def _execute_i...
class BaseModule(metaclass=ABCMeta): LOAD_ORDER = 0
random_line_split
Factory.js
/** * Factory based on OS output * */ var OS = require( "os" ); //Webcam types var FSWebcam = require( "./webcams/FSWebcam.js" ); var ImageSnapWebcam = require( "./webcams/ImageSnapWebcam.js" ); var WindowsWebcam = require( "./webcams/WindowsWebcam.js" ); //Main singleton var Factory = new function() { ...
return new Type( options ); }; }; Factory.Platform = OS.platform(); //OS Webcam types Factory.Types = { linux: FSWebcam, darwin: ImageSnapWebcam, fswebcam: FSWebcam, win32: WindowsWebcam, win64: WindowsWebcam }; //Export module.exports = Factory;
{ throw new Error( "Sorry, no webcam type specified yet for platform " + p ); }
conditional_block
Factory.js
/** * Factory based on OS output * */ var OS = require( "os" ); //Webcam types var FSWebcam = require( "./webcams/FSWebcam.js" ); var ImageSnapWebcam = require( "./webcams/ImageSnapWebcam.js" ); var WindowsWebcam = require( "./webcams/WindowsWebcam.js" );
var scope = this; //Main Class get scope.create = function( options, type ) { var p = type || Factory.Platform; var Type = Factory.Types[ p ]; if( ! Type ) { throw new Error( "Sorry, no webcam type specified yet for platform " + p ); } return new ...
//Main singleton var Factory = new function() {
random_line_split
__init__.py
# # 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. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
import numpy ver = [int(x) for x in numpy.version.version.split('.')[:2]] if ver < [1, 4]: raise Exception("MLlib requires NumPy 1.4+") __all__ = ['classification', 'clustering', 'feature', 'fpm', 'linalg', 'random', 'recommendation', 'regression', 'stat', 'tree', 'util']
random_line_split