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
recipes.py
from collections import defaultdict, namedtuple from minecraft_data.v1_8 import recipes as raw_recipes RecipeItem = namedtuple('RecipeItem', 'id meta amount') class Recipe(object): def __init__(self, raw): self.result = reformat_item(raw['result'], None) if 'ingredients' in raw: sel...
(self): """ Returns: dict: In the form { (item_id, metadata) -> [(x, y, amount), ...] } """ positions = defaultdict(list) for y, row in enumerate(self.in_shape): for x, (item_id, metadata, amount) in enumerate(row): positions[(item_id, meta...
ingredient_positions
identifier_name
serve_localhost.py
#! /usr/bin/env python3 # Invoke http.server to host a basic webserver on localhost /without/ caching. # Files served by http.server are usually cached by browsers, which makes testing and debugging # buggy. import http.server import os from functools import partial class NoCacheRequestHandler(http.server.SimpleHT...
(self): self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") self.send_header("Pragma", "no-cache") self.send_header("Expires", "0") super().end_headers() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument(...
end_headers
identifier_name
serve_localhost.py
#! /usr/bin/env python3 # Invoke http.server to host a basic webserver on localhost /without/ caching. # Files served by http.server are usually cached by browsers, which makes testing and debugging # buggy. import http.server import os from functools import partial class NoCacheRequestHandler(http.server.SimpleHT...
import argparse parser = argparse.ArgumentParser() parser.add_argument('--bind', '-b', default='localhost', metavar='ADDRESS', help='Specify alternate bind address ' '[default: localhost - pass \'\' if you want to serve remote clients]') parser.add_argum...
conditional_block
serve_localhost.py
#! /usr/bin/env python3 # Invoke http.server to host a basic webserver on localhost /without/ caching. # Files served by http.server are usually cached by browsers, which makes testing and debugging # buggy. import http.server import os from functools import partial class NoCacheRequestHandler(http.server.SimpleHT...
if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--bind', '-b', default='localhost', metavar='ADDRESS', help='Specify alternate bind address ' '[default: localhost - pass \'\' if you want to serve remo...
def end_headers(self): self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") self.send_header("Pragma", "no-cache") self.send_header("Expires", "0") super().end_headers()
identifier_body
serve_localhost.py
#! /usr/bin/env python3 # Invoke http.server to host a basic webserver on localhost /without/ caching. # Files served by http.server are usually cached by browsers, which makes testing and debugging # buggy. import http.server import os from functools import partial class NoCacheRequestHandler(http.server.SimpleHT...
super().end_headers() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--bind', '-b', default='localhost', metavar='ADDRESS', help='Specify alternate bind address ' '[default: localhost - pass \...
def end_headers(self): self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") self.send_header("Pragma", "no-cache") self.send_header("Expires", "0")
random_line_split
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
(err_msg: *const libc::c_char) -> String { let msg = unsafe { let bytes = CStr::from_ptr(err_msg).to_bytes(); str::from_utf8_unchecked(bytes).into() }; unsafe { ffi::sqlite3_free(err_msg as *mut libc::c_void) }; msg }
convert_to_string_and_free
identifier_name
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
else { Ok(()) } } pub fn rows_affected_by_last_query(&self) -> usize { unsafe { ffi::sqlite3_changes(self.internal_connection) as usize } } pub fn last_error_message(&self) -> String { let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection...
{ let msg = convert_to_string_and_free(err_msg); let error_kind = DatabaseErrorKind::__Unknown; Err(DatabaseError(error_kind, Box::new(msg))) }
conditional_block
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
Ok(()) } } pub fn rows_affected_by_last_query(&self) -> usize { unsafe { ffi::sqlite3_changes(self.internal_connection) as usize } } pub fn last_error_message(&self) -> String { let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection)) }; ...
{ let mut err_msg = ptr::null_mut(); let query = try!(CString::new(query)); let callback_fn = None; let callback_arg = ptr::null_mut(); unsafe { ffi::sqlite3_exec( self.internal_connection, query.as_ptr(), callback_fn, ...
identifier_body
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
}; match connection_status { ffi::SQLITE_OK => Ok(RawConnection { internal_connection: conn_pointer, }), err_code => { let message = super::error_message(err_code); Err(ConnectionError::BadConnection(message.into())) ...
let database_url = try!(CString::new(database_url)); let connection_status = unsafe { ffi::sqlite3_open(database_url.as_ptr(), &mut conn_pointer)
random_line_split
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } }
type IntoIter = Iter; fn into_iter(self) -> Iter { Iter { root: Some(self.root), dirs: Vec::new() } } } pub struct Iter { root: Option<PathBuf>, dirs: Vec<ReadDir>, } // TODO: Remove and implement Iterator for DeepWalk. impl Iterator for Iter { type Item = Result<DirEntry, Error>; ...
impl IntoIterator for DeepWalk { type Item = Result<DirEntry, Error>;
random_line_split
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } } impl IntoIterator for DeepWalk { type Item = Resu...
() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).root, Path::new(val)); } } #[test] fn deep_walk_into_iterator() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).into_iter().root, Some(PathBuf::from(val))); } } }
deep_walk_new
identifier_name
lib.rs
use std::path::{Path, PathBuf}; use std::fs::{self, ReadDir, DirEntry}; use std::io::Error; pub struct DeepWalk { root: PathBuf, } impl DeepWalk { pub fn new<P: AsRef<Path>>(root: P) -> Self { DeepWalk { root: root.as_ref().to_path_buf() } } } impl IntoIterator for DeepWalk { type Item = Resu...
#[test] fn deep_walk_into_iterator() { for val in get_test_roots() { assert_eq!(DeepWalk::new(val).into_iter().root, Some(PathBuf::from(val))); } } }
{ for val in get_test_roots() { assert_eq!(DeepWalk::new(val).root, Path::new(val)); } }
identifier_body
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
(&self, sender: ServerId, argsVec: ~[OscType]) -> RequestVoteRpc { let mut args = argsVec.move_iter(); let term: int = args.next().unwrap().unwrap_int() as int; let candidateId: ServerId = from_str::<ServerId>(args.next().unwrap().unwrap_string()).unwrap(); let lastLogIndex: int = args.next().unwrap().u...
parseRequestVote
identifier_name
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
// AppendEntries {term: int, leaderId: ServerId, prevLogIndex: int, // entries: ~[LogEntry], leaderCommitIndex: int}, fn parseAppendEntries(&self, sender: ServerId, argsVec: ~[OscType]) -> AppendEntriesRpc { let mut args = argsVec.move_iter(); let term = args.next().unwrap().unwrap_int() as int; le...
{ return match msg.address { ~"/appendEntries" => AppendEntries(self.parseAppendEntries(sender, msg.arguments)), ~"/requestVote" => RequestVote(self.parseRequestVote(sender, msg.arguments)), _ => fail!("woops no implementation for {}", msg.address) }; }
identifier_body
udptransport.rs
#[feature(struct_variant)]; #[feature(macro_rules)]; use osc::{OscType, OscMessage, OscWriter, OscReader}; use rpc::{ServerId, LogEntry, AppendEntriesRpc, AppendEntriesResponseRpc, RequestVoteRpc, RequestVoteResponseRpc, RaftRpc, AppendEntries, AppendEntriesResponse, RequestVote, RequestVoteRes...
prevLogIndex: prevLogIndex, prevLogTerm: prevLogTerm, entries: entries, leaderCommitIndex: leaderCommitIndex}; } // RequestVote {term: int, candidateId: ServerId, lastLogIndex: int, // lastLogTerm: int} fn parseRequestVote(&self, sender: ServerId, argsVec: ~[...
random_line_split
balancedColumnTreeBuilder.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.0.2 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : ...
() { } BalancedColumnTreeBuilder.prototype.agWire = function (loggerFactory) { this.logger = loggerFactory.create('BalancedColumnTreeBuilder'); }; BalancedColumnTreeBuilder.prototype.createBalancedColumnGroups = function (abstractColDefs) { // column key creator dishes out unique column ...
BalancedColumnTreeBuilder
identifier_name
balancedColumnTreeBuilder.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.0.2 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : ...
BalancedColumnTreeBuilder.prototype.agWire = function (loggerFactory) { this.logger = loggerFactory.create('BalancedColumnTreeBuilder'); }; BalancedColumnTreeBuilder.prototype.createBalancedColumnGroups = function (abstractColDefs) { // column key creator dishes out unique column id's in a ...
{ }
identifier_body
balancedColumnTreeBuilder.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.0.2 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : ...
if (colDefNoType.headerGroupShow !== undefined) { console.warn('ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3'); } } }; // if object has children, we assume it's a...
} if (colDefNoType.headerGroup !== undefined) { console.warn('ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3'); }
random_line_split
professional-email-card.tsx
import { Gridicon } from '@automattic/components'; import { useShoppingCart } from '@automattic/shopping-cart'; import { translate } from 'i18n-calypso'; import { useState } from 'react'; import { useSelector } from 'react-redux'; import poweredByTitanLogo from 'calypso/assets/images/email-providers/titan/powered-by-ti...
const props: TitanProductProps = { domain: selectedDomainName, quantity: validatedTitanMailboxes.length, extra: { email_users: validatedTitanMailboxes.map( transformMailboxForCart ), new_quantity: validatedTitanMailboxes.length, }, }; const cartItem = intervalLength === IntervalLength.MO...
{ return; }
conditional_block
professional-email-card.tsx
import { Gridicon } from '@automattic/components'; import { useShoppingCart } from '@automattic/shopping-cart'; import { translate } from 'i18n-calypso'; import { useState } from 'react'; import { useSelector } from 'react-redux'; import poweredByTitanLogo from 'calypso/assets/images/email-providers/titan/powered-by-ti...
}; const cartItem = intervalLength === IntervalLength.MONTHLY ? titanMailMonthly( props ) : titanMailYearly( props ); addToCartAndCheckout( shoppingCartManager, cartItem, setAddingToCart, selectedSite?.slug ?? '' ); }; const onTitanFormReturnKeyPress = noop; professionalEmail.onExp...
quantity: validatedTitanMailboxes.length, extra: { email_users: validatedTitanMailboxes.map( transformMailboxForCart ), new_quantity: validatedTitanMailboxes.length, },
random_line_split
save.py
""" Simple utils to save and load from disk. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals # TODO(rbharath): Use standard joblib once old-data has been regenerated. import joblib from sklearn.externals import joblib as old_joblib import gzip import pi...
if verbose: print(string) def save_to_disk(dataset, filename, compress=3): """Save a dataset to file.""" joblib.dump(dataset, filename, compress=compress) def get_input_type(input_file): """Get type of input file. Must be csv/pkl.gz/sdf file.""" filename, file_extension = os.path.splitext(input_file) ...
def log(string, verbose=True): """Print string if verbose."""
random_line_split
save.py
""" Simple utils to save and load from disk. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals # TODO(rbharath): Use standard joblib once old-data has been regenerated. import joblib from sklearn.externals import joblib as old_joblib import gzip import pi...
def load_from_disk(filename): """Load a dataset from file.""" name = filename if os.path.splitext(name)[1] == ".gz": name = os.path.splitext(name)[0] if os.path.splitext(name)[1] == ".pkl": return load_pickle_from_disk(filename) elif os.path.splitext(name)[1] == ".joblib": try: return jobl...
log("About to start loading CSV from %s" % filename, verbose) for df in pd.read_csv(filename, chunksize=shard_size): log("Loading shard %d of size %s." % (shard_num, str(shard_size)), verbose) df = df.replace(np.nan, str(""), regex=True) shard_num += 1 yield df
conditional_block
save.py
""" Simple utils to save and load from disk. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals # TODO(rbharath): Use standard joblib once old-data has been regenerated. import joblib from sklearn.externals import joblib as old_joblib import gzip import pi...
def load_data(input_files, shard_size=None, verbose=True): """Loads data from disk. For CSV files, supports sharded loading for large files. """ if not len(input_files): return input_type = get_input_type(input_files[0]) if input_type == "sdf": if shard_size is not None: log("Ignoring ...
"""Get type of input file. Must be csv/pkl.gz/sdf file.""" filename, file_extension = os.path.splitext(input_file) # If gzipped, need to compute extension again if file_extension == ".gz": filename, file_extension = os.path.splitext(filename) if file_extension == ".csv": return "csv" elif file_extensi...
identifier_body
save.py
""" Simple utils to save and load from disk. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals # TODO(rbharath): Use standard joblib once old-data has been regenerated. import joblib from sklearn.externals import joblib as old_joblib import gzip import pi...
(dataset, filename, compress=3): """Save a dataset to file.""" joblib.dump(dataset, filename, compress=compress) def get_input_type(input_file): """Get type of input file. Must be csv/pkl.gz/sdf file.""" filename, file_extension = os.path.splitext(input_file) # If gzipped, need to compute extension again i...
save_to_disk
identifier_name
app.component.ts
import { Component,OnChanges,HostListener } from '@angular/core'; import '../js/test.js'; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { text = ''; rText = ''; key; old...
handleKeyboardEvent(event: KeyboardEvent) { this.key = event.key; if ((event.keyCode ? event.keyCode : event.which) == 13) { //Enter keycode this.generate(); } } ngDoCheck(){ if(this.oldLength!=this.length){ this.oldLength = this.length; if(this.length==42){ console.log(':)'); } } ...
this.generate(); } @HostListener('document:keypress', ['$event'])
random_line_split
app.component.ts
import { Component,OnChanges,HostListener } from '@angular/core'; import '../js/test.js'; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { text = ''; rText = ''; key; old...
ngDoCheck(){ if(this.oldLength!=this.length){ this.oldLength = this.length; if(this.length==42){ console.log(':)'); } } this.rText = this.text.split("").reverse().join("").substring(0,this.length)+(this.text.length>this.length?"...":""); } generate(){ this.text = ''; for( var i=0;...
{ this.key = event.key; if ((event.keyCode ? event.keyCode : event.which) == 13) { //Enter keycode this.generate(); } }
identifier_body
app.component.ts
import { Component,OnChanges,HostListener } from '@angular/core'; import '../js/test.js'; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { text = ''; rText = ''; key; old...
(){ this.text = ''; for( var i=0; i < this.length; i++ ) this.text += possible.charAt(Math.floor(Math.random() * possible.length)); } }
generate
identifier_name
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
(&mut self, instance_id: InstanceId, params: Vec<u8>) -> Self::Output { const METHOD_DESCRIPTOR: MethodDescriptor<'static> = MethodDescriptor::new(CONFIGURE_INTERFACE_NAME, 0); self.generic_call_mut(instance_id, METHOD_DESCRIPTOR, params) } fn apply_config(&mut self, instance_id: In...
verify_config
identifier_name
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
}
{ const METHOD_DESCRIPTOR: MethodDescriptor<'static> = MethodDescriptor::new(CONFIGURE_INTERFACE_NAME, 1); self.generic_call_mut(instance_id, METHOD_DESCRIPTOR, params) }
identifier_body
configure.rs
// Copyright 2020 The Exonum Team // // 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 i...
/// So the service instance should save them by itself if it is important for /// the service business logic. /// /// This method can be triggered at any time and does not follow the general transaction /// execution workflow, so the errors returned might be ignored. /// /// # Execution poli...
random_line_split
empty-state.component.ts
import { Component, DoCheck, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { cloneDeep, defaults, isEqual } from 'lodash'; import { Action } from '../action/action'; import { EmptyStateConfig } from './empty-state-config'; /** * Component for rendering an empty ...
// Do a deep compare on config if (!isEqual(this.config, this.prevConfig)) { this.setupConfig(); } } /** * Set up default config */ protected setupConfig(): void { if (this.config !== undefined) { defaults(this.config, this.defaultConfig); } else { this.config = cloneD...
* Check if the component config has changed */ ngDoCheck(): void {
random_line_split
empty-state.component.ts
import { Component, DoCheck, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { cloneDeep, defaults, isEqual } from 'lodash'; import { Action } from '../action/action'; import { EmptyStateConfig } from './empty-state-config'; /** * Component for rendering an empty ...
/** * Set up default config */ protected setupConfig(): void { if (this.config !== undefined) { defaults(this.config, this.defaultConfig); } else { this.config = cloneDeep(this.defaultConfig); } this.prevConfig = cloneDeep(this.config); } // Private private handleAction(a...
{ // Do a deep compare on config if (!isEqual(this.config, this.prevConfig)) { this.setupConfig(); } }
identifier_body
empty-state.component.ts
import { Component, DoCheck, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { cloneDeep, defaults, isEqual } from 'lodash'; import { Action } from '../action/action'; import { EmptyStateConfig } from './empty-state-config'; /** * Component for rendering an empty ...
(): void { // Do a deep compare on config if (!isEqual(this.config, this.prevConfig)) { this.setupConfig(); } } /** * Set up default config */ protected setupConfig(): void { if (this.config !== undefined) { defaults(this.config, this.defaultConfig); } else { this.conf...
ngDoCheck
identifier_name
empty-state.component.ts
import { Component, DoCheck, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { cloneDeep, defaults, isEqual } from 'lodash'; import { Action } from '../action/action'; import { EmptyStateConfig } from './empty-state-config'; /** * Component for rendering an empty ...
} /** * Set up default config */ protected setupConfig(): void { if (this.config !== undefined) { defaults(this.config, this.defaultConfig); } else { this.config = cloneDeep(this.defaultConfig); } this.prevConfig = cloneDeep(this.config); } // Private private handleActi...
{ this.setupConfig(); }
conditional_block
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
<T: Trait>() {} assert_impl::<HasCastInTraitImpl<N, { N as u128 }>>(); assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); } pub fn use_trait_impl_2<const N: usize>() where EvaluatableU128<{N as _}>:, ...
assert_impl
identifier_name
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
fn main() {}
assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); }
random_line_split
abstract-const-as-cast-4.rs
// check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Trait {} pub struct EvaluatableU128<const N: u128>; struct HasCastInTraitImpl<const N: usize, const M: u128>; impl<const O: usize> Trait for HasCastInTraitImpl<O, { O as u128 }> {} pub fn use_trait_impl<const N: usize>() where Evalua...
fn main() {}
{ fn assert_impl<T: Trait>() {} assert_impl::<HasCastInTraitImpl<N, { N as u128 }>>(); assert_impl::<HasCastInTraitImpl<N, { N as _ }>>(); assert_impl::<HasCastInTraitImpl<12, { 12 as u128 }>>(); assert_impl::<HasCastInTraitImpl<13, 13>>(); }
identifier_body
static-reference-to-fn-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn finished(_: &mut StateMachineIter) -> Option<(&'static str)> { return None; } fn state_iter() -> StateMachineIter<'static> { StateMachineIter { statefn: &state1 //~ ERROR borrowed value does not live long enough } } fn main() { let mut it = state_iter(); println!("{}",it.next()); ...
{ self_.statefn = &finished; //~^ ERROR borrowed value does not live long enough return Some("state3"); }
identifier_body
static-reference-to-fn-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// 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. This file may not be copied, modified, or distributed // except according to those terms. struct StateMachine...
// http://rust-lang.org/COPYRIGHT. //
random_line_split
static-reference-to-fn-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self_: &mut StateMachineIter) -> Option<&'static str> { self_.statefn = &state2; //~^ ERROR borrowed value does not live long enough return Some("state1"); } fn state2(self_: &mut StateMachineIter) -> Option<(&'static str)> { self_.statefn = &state3; //~^ ERROR borrowed value does not live long en...
state1
identifier_name
xinput.py
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscopio Tecnologia # Author: Marcelo Jorge Vieira <metal@holoscopio.com> # Author: Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
def config(self, dict): num, den = Fract.fromdecimal(dict["framerate"]) caps = gst.caps_from_string( "video/x-raw-rgb, framerate=%d/%d" % (num, den) ) self.capsfilter.set_property("caps", caps)
Input.__init__(self, CAPABILITIES) self.video_src = gst.element_factory_make("ximagesrc", "video_src") # Setting format to time, to work with input-selector, since they're # were not working together in version 0.10.18-1 from Debian. # This should be fixed in ximagesrc's code and input-...
identifier_body
xinput.py
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscopio Tecnologia # Author: Marcelo Jorge Vieira <metal@holoscopio.com> # Author: Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
# with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import gobject import pygst pygst.require("0.10") import gst from core import Input, INPUT_TYPE_VIDEO from sltv.utils import Fract CAPABILITIES = INPUT_TYPE_VIDEO class XInput(Input...
# You should have received a copy of the GNU General Public License along
random_line_split
xinput.py
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscopio Tecnologia # Author: Marcelo Jorge Vieira <metal@holoscopio.com> # Author: Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
(Input): def __init__(self): Input.__init__(self, CAPABILITIES) self.video_src = gst.element_factory_make("ximagesrc", "video_src") # Setting format to time, to work with input-selector, since they're # were not working together in version 0.10.18-1 from Debian. # This shou...
XInput
identifier_name
settings.py
""" Django settings for magnet project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os ...
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Our apps 'magnet.apps.users', # 3rd Party apps 'crispy_forms', 'd...
random_line_split
settings.py
""" Django settings for magnet project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os ...
try: from .local_settings import * except: pass
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True
conditional_block
_load_balancer_network_interfaces_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_group_name, # type: str load_balancer_name, # type: str **kwargs # ...
__init__
identifier_name
_load_balancer_network_interfaces_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
def list( self, resource_group_name, # type: str load_balancer_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.NetworkInterfaceListResult"] """Gets associated load balancer network interfaces. :param resource_group_name: ...
self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
identifier_body
_load_balancer_network_interfaces_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list...
random_line_split
_load_balancer_network_interfaces_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('Net...
url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), ...
conditional_block
create.py
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import sqlalchemy import ckan.plugins.toolkit as toolkit import ckan.lib.dictization.model_dictize as model_dictize from ckan.logic import NotAuthorized import logging log = logging.getLogger(__name__) from sqlalchemy import Column, String, ...
def make_uuid(): return unicode(uuid.uuid4()) class Article(base): __tablename__ = 'articles' id = Column(types.UnicodeText, primary_key=True, default=make_uuid) title = Column(types.UnicodeText, nullable=False, unique=True) content = Column(types.UnicodeText, nullable=False) author = Column...
return datetime.now()
identifier_body
create.py
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import sqlalchemy import ckan.plugins.toolkit as toolkit import ckan.lib.dictization.model_dictize as model_dictize from ckan.logic import NotAuthorized import logging log = logging.getLogger(__name__) from sqlalchemy import Column, String, ...
(context, data_dict): model = context['model'] model.Session.add(Article(title= data_dict['title'], author="ckan", content= data_dict['content'])) model.Session.commit() return True
article_create
identifier_name
create.py
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import sqlalchemy import ckan.plugins.toolkit as toolkit import ckan.lib.dictization.model_dictize as model_dictize from ckan.logic import NotAuthorized import logging log = logging.getLogger(__name__) from sqlalchemy import Column, String, ...
id = Column(types.UnicodeText, primary_key=True, default=make_uuid) title = Column(types.UnicodeText, nullable=False, unique=True) content = Column(types.UnicodeText, nullable=False) author = Column(types.UnicodeText, nullable=False) created_date = Column(DateTime, default = _get_datetime) upda...
def make_uuid(): return unicode(uuid.uuid4()) class Article(base): __tablename__ = 'articles'
random_line_split
test_data_root.py
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): specs = yield self.callGet(('application.spec',)) [self.validateData(s) for s in specs] for s in specs: # only test an endpoint that is reasonably stable if s['path...
self.master.data.setServiceParent(self.master)
random_line_split
test_data_root.py
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
(endpoint.EndpointMixin, unittest.TestCase): endpointClass = root.SpecEndpoint resourceTypeClass = root.Spec def setUp(self): self.setUpEndpoint() # replace fakeConnector with real DataConnector self.master.data.disownServiceParent() self.master.data = connector.DataConnect...
SpecEndpoint
identifier_name
test_data_root.py
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): specs = yield self.callGet(('application.spec',)) [self.validateData(s) for s in specs] for s in specs: # only test an endpoint that is reasonably stable if s['pa...
self.setUpEndpoint() # replace fakeConnector with real DataConnector self.master.data.disownServiceParent() self.master.data = connector.DataConnector() self.master.data.setServiceParent(self.master)
identifier_body
test_data_root.py
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
self.assertEqual(s, {'path': 'master', 'type': 'master', 'type_spec': {'fields': [{'name': 'active', 'type': 'boolean', ...
continue
conditional_block
linesearch_step.py
# Copyright 2020 Tensorforce Team. 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 la...
self.line_search = self.submodule( name='line_search', module='line_search', modules=solver_modules, max_iterations=max_iterations, backtracking_factor=backtracking_factor ) def initialize_given_variables(self, *, variables): super().initialize_given_variables(varia...
""" Line-search-step update modifier, which performs a line search on the update step returned by the given optimizer to find a potentially superior smaller step size (specification key: `linesearch_step`). Args: optimizer (specification): Optimizer configuration (<span style="color...
identifier_body
linesearch_step.py
# Copyright 2020 Tensorforce Team. 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 la...
): super().__init__(optimizer=optimizer, name=name, arguments_spec=arguments_spec) self.line_search = self.submodule( name='line_search', module='line_search', modules=solver_modules, max_iterations=max_iterations, backtracking_factor=backtracking_factor ) def i...
def __init__( self, *, optimizer, max_iterations, backtracking_factor=0.75, name=None, arguments_spec=None
random_line_split
linesearch_step.py
# Copyright 2020 Tensorforce Team. 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 la...
with tf.control_dependencies(control_inputs=assignments): return fn_loss(**arguments.to_kwargs()) _deltas = self.line_search.solve( arguments=arguments, x_init=_deltas, base_value=loss_before, zero_...
assignments.append(variable.assign_add(delta=delta, read_value=False))
conditional_block
linesearch_step.py
# Copyright 2020 Tensorforce Team. 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 la...
(self, *, arguments, variables, fn_loss, **kwargs): loss_before = fn_loss(**arguments.to_kwargs()) with tf.control_dependencies(control_inputs=(loss_before,)): deltas = self.optimizer.step( arguments=arguments, variables=variables, fn_loss=fn_loss, **kwargs ) ...
step
identifier_name
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
{ /// If specified, limits the number of `Scene::tick` calls per second to this value. /// `run_scene` ensures this limitation by sleeping after each tick as needed. pub tpslimit: Option<uint>, /// If specified, limits the number of `Scene::render` calls per second to this value. /// Due to the imp...
SceneOptions
identifier_name
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
} /// A command returned by `Scene`'s `tick` method. pub enum SceneCommand { /// Continues displaying this scene. Continue, /// Pushes a new `Scene` to the scene stack, making it the active scene. The current scene is /// stopped (after calling `deactivate`) until the new scene returns `PopScene` comm...
{ SceneOptions { fpslimit: Some(fps), ..self } }
identifier_body
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
impl SceneOptions { /// Creates default options for the scene. pub fn new() -> SceneOptions { SceneOptions { tpslimit: None, fpslimit: None } } /// Replaces `tpslimit` field with given value. pub fn tpslimit(self, tps: uint) -> SceneOptions { SceneOptions { tpslimit: Some(tps), ..se...
}
random_line_split
scene.rs
// This is a part of Sonorous. // Copyright (c) 2005, 2007, 2009, 2012, 2013, 2014, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! Scene management. use std::io::timer::sleep; use std::time::Duration; use sdl::get_ticks; use ui::common::Ticker; /// Options used by the scene to customize the scene ...
_ => {} } match result { SceneCommand::Continue => { panic!("impossible"); } SceneCommand::Push(newscene) => { stack.push(current); current = newscene; } SceneCommand::Replace => { ...
{ let opts = current.scene_options(); let mintickdelay = opts.tpslimit.map_or(0, |tps| 1000 / tps); let interval = opts.fpslimit.map_or(0, |fps| 1000 / fps); let mut ticker = Ticker::with_interval(interval); loop { let t...
conditional_block
price.service.ts
import * as memotyCache from 'memory-cache'; import * as moment from 'moment'; import * as Bluebird from 'bluebird'; import * as _ from 'lodash'; import axios from 'axios'; import { HubData } from '../../eve-client/api/id-names-mapper'; const PRICE_ENDPOINT = 'https://esi.tech.ccp.is/latest/markets/{regionId}/orders/?...
result.sell = _.minBy(_.filter(prices, (order) => { return order.location_id === stationId && !order.is_buy_order; }), record => record.price) || prices[0]; return result; } export interface PriceResponse { order_id: number; type_id: number; location_id: number; volume_total: numbe...
result.buy = _.maxBy(_.filter(prices, (order) => { return order.location_id === stationId && order.is_buy_order; }), record => record.price) || prices[0];
random_line_split
price.service.ts
import * as memotyCache from 'memory-cache'; import * as moment from 'moment'; import * as Bluebird from 'bluebird'; import * as _ from 'lodash'; import axios from 'axios'; import { HubData } from '../../eve-client/api/id-names-mapper'; const PRICE_ENDPOINT = 'https://esi.tech.ccp.is/latest/markets/{regionId}/orders/?...
export interface PriceResponse { order_id: number; type_id: number; location_id: number; volume_total: number; volume_remain: number; min_volume: number; price: number; is_buy_order: number; duration: number; issued: string; range: string; }
{ let result = new PriceServiceResponse(); result.buy = _.maxBy(_.filter(prices, (order) => { return order.location_id === stationId && order.is_buy_order; }), record => record.price) || prices[0]; result.sell = _.minBy(_.filter(prices, (order) => { return order.location_id === stationId...
identifier_body
price.service.ts
import * as memotyCache from 'memory-cache'; import * as moment from 'moment'; import * as Bluebird from 'bluebird'; import * as _ from 'lodash'; import axios from 'axios'; import { HubData } from '../../eve-client/api/id-names-mapper'; const PRICE_ENDPOINT = 'https://esi.tech.ccp.is/latest/markets/{regionId}/orders/?...
console.info(`price for ${priceSearchKey} not found in cache, executing CCP call`); return new Bluebird<PriceServiceResponse>((resolve, reject) => { axios.get(PRICE_ENDPOINT.replace('{regionId}', regionId.toString()).replace('{itemId}', itemId.toString())) .then(result => { ...
{ console.info(`price for ${priceSearchKey} has been found in cache, skipping CCP call`); if (pricesOrError.code && pricesOrError.code === 404) { return Bluebird.reject(pricesOrError); } return Bluebird.resolve(filterPrices(pricesOrError, stationId)); }
conditional_block
price.service.ts
import * as memotyCache from 'memory-cache'; import * as moment from 'moment'; import * as Bluebird from 'bluebird'; import * as _ from 'lodash'; import axios from 'axios'; import { HubData } from '../../eve-client/api/id-names-mapper'; const PRICE_ENDPOINT = 'https://esi.tech.ccp.is/latest/markets/{regionId}/orders/?...
{ sell: PriceResponse; buy: PriceResponse; } export function getPriceForItemOnStation(itemId: number, regionId: number, stationId: number) { let priceSearchKey = '' + itemId + regionId; let pricesOrError: PriceResponse[] & { code: number } = memotyCache.get(priceSearchKey); if (pricesOrError) { ...
PriceServiceResponse
identifier_name
cssbag.ts
/** The MIT License (MIT) Copyright(c) 2016 Maxim V.Tsapov */ import { Utils, BasePropBag } from "jriapp_shared"; import { DomUtils } from "jriapp/utils/dom"; const utils = Utils, checks = utils.check, dom = DomUtils; // wraps HTMLElement to add or remove classNames using data binding export class CSSBag extends ...
else if (checks.isString(val)) { dom.setClasses([this._el], val.split(" ")); } return; } //set individual classes dom.setClass([this._el], name, !val); } toString() { return "CSSBag"; } }
dom.setClasses([this._el], <string[]>val); }
conditional_block
cssbag.ts
/** The MIT License (MIT) Copyright(c) 2016 Maxim V.Tsapov */ import { Utils, BasePropBag } from "jriapp_shared"; import { DomUtils } from "jriapp/utils/dom"; const utils = Utils, checks = utils.check, dom = DomUtils; // wraps HTMLElement to add or remove classNames using data binding export class CSSBag extends ...
if (name === "*") { if (!val) { //remove all classes dom.removeClass([this._el], null); } else if (checks.isArray(val)) { dom.setClasses([this._el], <string[]>val); } else if (checks.isString(val)) { ...
random_line_split
cssbag.ts
/** The MIT License (MIT) Copyright(c) 2016 Maxim V.Tsapov */ import { Utils, BasePropBag } from "jriapp_shared"; import { DomUtils } from "jriapp/utils/dom"; const utils = Utils, checks = utils.check, dom = DomUtils; // wraps HTMLElement to add or remove classNames using data binding export class CSSBag extends ...
//implement IPropertyBag setProp(name: string, val: any): void { if (val === checks.undefined) return; if (name === "*") { if (!val) { //remove all classes dom.removeClass([this._el], null); } else if (checks.isArray...
super(); this._el = el; }
identifier_body
cssbag.ts
/** The MIT License (MIT) Copyright(c) 2016 Maxim V.Tsapov */ import { Utils, BasePropBag } from "jriapp_shared"; import { DomUtils } from "jriapp/utils/dom"; const utils = Utils, checks = utils.check, dom = DomUtils; // wraps HTMLElement to add or remove classNames using data binding export class CSSBag extends ...
{ return "CSSBag"; } }
String()
identifier_name
setup.py
from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-Lcdplate', version=get_versio...
], }, classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia...
'mock >= 1.0', ], entry_points={ 'mopidy.ext': [ 'lcdplate = mopidy_lcdplate:Extension',
random_line_split
setup.py
from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename):
setup( name='Mopidy-Lcdplate', version=get_version('mopidy_lcdplate/__init__.py'), url='https://github.com/gimunu/mopidy-lcdplate', license='Apache License, Version 2.0', author='Umberto De Giovannini', author_email='umberto.degiovannini@gmail.com', description='Modipy extension for Adafr...
content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version']
identifier_body
setup.py
from __future__ import unicode_literals import re from setuptools import find_packages, setup def
(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-Lcdplate', version=get_version('mopidy_lcdplate/__init__.py'), url='https://github.com/gimunu/mopidy-lcdplate', license='Apache Licens...
get_version
identifier_name
animatedText.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restric...
nodeToMeasure: D3.Selection, availableWidth: number, seedFontHeight: number, iteration: number): number { // Too many attempts - just return what we have so we don't sacrifice perf if (iteration > 10) return seedFontHeight; ...
tAdjustedFontHeightCore(
identifier_name
animatedText.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restric...
let i = d3.interpolate(interpolatedValue, d); return function (t) { let num = i(t); this.textContent = formatter.format(num); }; }); } SVGUtil.flus...
let interpolatedValue = startValue; textElementUpdate .transition() .duration(duration) .tween('text', function (d) {
random_line_split
animatedText.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restric...
private getAdjustedFontHeightCore( nodeToMeasure: D3.Selection, availableWidth: number, seedFontHeight: number, iteration: number): number { // Too many attempts - just return what we have so we don't sacrifice perf if (iteration > 10) ...
// set up the node so we don't keep appending/removing it during the computation let nodeSelection = this.svg.append('text').text(textToMeasure); let fontHeight = this.getAdjustedFontHeightCore( nodeSelection, availableWidth, seedFont...
identifier_body
controller.py
Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This module provides the following classes: AlienFXController: base class for AlienFX controller chips """ from builtins ...
zone_codes = self._get_zone_codes(themefile.get_zone_names(item)) loop_items = themefile.get_loop_items(item) loop_cmds = self._make_loop_cmds( themefile, zone_codes, block, loop_items) if (loop_cmds): block += 1 for loop_cmd in loop_cm...
conditional_block
controller.py
should have received a copy of the GNU General Public License # along with alienfx. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This ...
(self, reset_name): """ Given the name of a reset action, return its code. """ for reset in self.reset_types: if reset_name == self.reset_types[reset]: return reset logging.warning("Unknown reset type: {}".format(reset_name)) return 0 def _make_lo...
_get_reset_code
identifier_name
controller.py
should have received a copy of the GNU General Public License # along with alienfx. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This ...
def pkt_to_string(self, pkt_bytes): """ Return a human readable string representation of an AlienFX command packet. """ return self.cmd_packet.pkt_to_string(pkt_bytes, self) def _get_no_zone_code(self): """ Return a zone code corresponding to all non-vis...
if errcount > 50: logging.error("Controller status could not be retrieved. Is the device already in use?") quit(-99)
random_line_split
controller.py
should have received a copy of the GNU General Public License # along with alienfx. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This ...
def get_state_name(self, state): """ Given a state number, return a string state name """ for state_name in self.state_map: if self.state_map[state_name] == state: return state_name return "UNKNOWN" def get_reset_type_name(self, num): ...
""" Given 3 bytes of a command packet, return a string zone name corresponding to it """ zone_mask = (pkt[0] << 16) + (pkt[1] << 8) + pkt[2] zone_name = "" for zone in self.zone_map: bit_mask = self.zone_map[zone] if zone_mask & bit_mask: ...
identifier_body
asciidoc2html.py
If not, see <https://www.gnu.org/licenses/>. """Generate the html documentation based on the asciidoc files.""" from typing import List, Optional import re import os import sys import subprocess import shutil import tempfile import argparse import io import pathlib REPO_ROOT = pathlib.Path(__file__).resolve().pare...
for item_path in pathlib.Path(REPO_ROOT).rglob('*.asciidoc'): if item_path.stem in ['header', 'OpenSans-License']: continue self._build_website_file(item_path.parent, item_path.name) copy = {'icons': 'icons', 'doc/img': 'doc/img', 'www/media': 'media/'} ...
assert self._themedir is not None # for mypy shutil.copy(theme_file, self._themedir) assert self._website is not None # for mypy outdir = pathlib.Path(self._website)
random_line_split
asciidoc2html.py
'tmp' self._tempdir.mkdir(parents=True) self._themedir.mkdir(parents=True) def cleanup(self) -> None: """Clean up the temporary home directory for asciidoc.""" if self._homedir is not None and not self._failed: shutil.rmtree(str(self._homedir)) def build(self) -> N...
main
identifier_name
asciidoc2html.py
If not, see <https://www.gnu.org/licenses/>. """Generate the html documentation based on the asciidoc files.""" from typing import List, Optional import re import os import sys import subprocess import shutil import tempfile import argparse import io import pathlib REPO_ROOT = pathlib.Path(__file__).resolve().pare...
def build(self) -> None: """Build either the website or the docs.""" if self._website: self._build_website() else: self._build_docs() self._copy_images() def _build_docs(self) -> None: """Render .asciidoc files to .html sites.""" fil...
shutil.rmtree(str(self._homedir))
conditional_block
asciidoc2html.py
from typing import List, Optional import re import os import sys import subprocess import shutil import tempfile import argparse import io import pathlib REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] DOC_DIR = REPO_ROOT / 'qutebrowser' / 'html' / 'doc' sys.path.insert(0, str(REPO_ROOT)) from scripts import...
"""Call asciidoc for the given files. Args: src: The source .asciidoc file. dst: The destination .html file, or None to auto-guess. *args: Additional arguments passed to asciidoc. """ print("Calling asciidoc for {}...".format(src.name)) assert self._c...
identifier_body
lda_testing.py
__author__ = 'fpena' import numpy as np import lda import lda.datasets def
(): # document-term matrix X = lda.datasets.load_reuters() print("type(X): {}".format(type(X))) print("shape: {}\n".format(X.shape)) # the vocab vocab = lda.datasets.load_reuters_vocab() print("type(vocab): {}".format(type(vocab))) print("len(vocab): {}\n".format(len(vocab))) # tit...
run
identifier_name
lda_testing.py
__author__ = 'fpena' import numpy as np import lda import lda.datasets def run(): # document-term matrix
print("-- doc : {}".format(titles[doc_id])) model = lda.LDA(n_topics=20, n_iter=500, random_state=1) model.fit(X) topic_word = model.topic_word_ print("type(topic_word): {}".format(type(topic_word))) print("shape: {}".format(topic_word.shape)) for n in range(5): sum_pr = sum(topic...
X = lda.datasets.load_reuters() print("type(X): {}".format(type(X))) print("shape: {}\n".format(X.shape)) # the vocab vocab = lda.datasets.load_reuters_vocab() print("type(vocab): {}".format(type(vocab))) print("len(vocab): {}\n".format(len(vocab))) # titles for each story titles = lda...
identifier_body
lda_testing.py
__author__ = 'fpena' import numpy as np import lda import lda.datasets def run(): # document-term matrix X = lda.datasets.load_reuters() print("type(X): {}".format(type(X))) print("shape: {}\n".format(X.shape)) # the vocab vocab = lda.datasets.load_reuters_vocab() print("type(vocab): {}...
if word > 1: print(word)
conditional_block
lda_testing.py
__author__ = 'fpena' import numpy as np import lda import lda.datasets def run(): # document-term matrix X = lda.datasets.load_reuters() print("type(X): {}".format(type(X)))
vocab = lda.datasets.load_reuters_vocab() print("type(vocab): {}".format(type(vocab))) print("len(vocab): {}\n".format(len(vocab))) # titles for each story titles = lda.datasets.load_reuters_titles() print("type(titles): {}".format(type(titles))) print("len(titles): {}\n".format(len(titles)...
print("shape: {}\n".format(X.shape)) # the vocab
random_line_split
es5.demo.config.ts
import * as fs from 'fs'; import * as minimist from 'minimist'; import * as path from 'path'; import {baseConfig} from './es5.base.config';
// Allow for specific demos to built with a --demos=<someName>,<someOtherName> // CLI format. const args = minimist(process.argv.slice(2)); const specified: string[] = args.demos ? args.demos.split(',') : []; const getDemos = source => { return fs.readdirSync(source) .filter(name => path.extname(name) === '.ht...
random_line_split
getting_started.py
from dcgpy import expression_gdual_double as expression from dcgpy import kernel_set_gdual_double as kernel_set from pyaudi import gdual_double as gdual # 1- Instantiate a random expression using the 4 basic arithmetic operations ks = kernel_set(["sum", "diff", "div", "mul"]) ex = expression(inputs = 1, ...
n_eph = 0, seed = 4232123212) # 2 - Define the symbol set to be used in visualizing the expression # (in our case, 1 input variable named "x") and visualize the expression in_sym = ["x"] print("Expression:", ex(in_sym)[0]) # 3 - Print the simplified expression print("Simplified expre...
kernels = ks(),
random_line_split
controller.js
import angular from 'angular'; class PhotosController { /** @ngInject */ constructor($scope, $stateParams, $state, photosGallery) { this.$scope = $scope; this.$stateParams = $stateParams; this.$state = $state; this.photosGallery = photosGallery; this.photosByMonth = {}; this.initWatchers(...
(photo) { const date = new Date(photo.metadata.createDate); const month = date.toLocaleString('en', { month: 'short' }); return `${month} ${date.getFullYear()} `; } } export default angular.module('photos.controller', []) .controller('photosController', PhotosController);
monthLabel
identifier_name
controller.js
import angular from 'angular'; class PhotosController { /** @ngInject */ constructor($scope, $stateParams, $state, photosGallery)
initWatchers() { this.$scope.$watch(() => this.photosGallery.photos, this.groupPhotosByMonth.bind(this)); } showPhoto(id) { this.$state.go('photo-detail', { id }); } showPage(page) { this.$state.go( 'photos', { page, search: this.photosGallery.search }, { location: 'replace' ...
{ this.$scope = $scope; this.$stateParams = $stateParams; this.$state = $state; this.photosGallery = photosGallery; this.photosByMonth = {}; this.initWatchers(); this.showPhotos(); }
identifier_body
controller.js
import angular from 'angular'; class PhotosController { /** @ngInject */ constructor($scope, $stateParams, $state, photosGallery) { this.$scope = $scope; this.$stateParams = $stateParams; this.$state = $state; this.photosGallery = photosGallery; this.photosByMonth = {}; this.initWatchers(...
this.photosGallery.showPhotos({ page, search }); } pageButtonClass(page) { if (page === this.photosGallery.currentPage) { return 'md-raised md-primary'; } return 'md-raised custom'; } groupPhotosByMonth(photos) { const res = {}; photos.forEach((photo) => { const month = thi...
random_line_split
controller.js
import angular from 'angular'; class PhotosController { /** @ngInject */ constructor($scope, $stateParams, $state, photosGallery) { this.$scope = $scope; this.$stateParams = $stateParams; this.$state = $state; this.photosGallery = photosGallery; this.photosByMonth = {}; this.initWatchers(...
return 'md-raised custom'; } groupPhotosByMonth(photos) { const res = {}; photos.forEach((photo) => { const month = this.monthLabel(photo); if (!res[month]) { res[month] = []; } res[month].push(photo); }); this.photosByMonth = res; console.log("PhotosContro...
{ return 'md-raised md-primary'; }
conditional_block
app.py
import sys sys.path.append('../..') import web from web.contrib.template import render_jinja from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from social.utils import setting_name from social.apps.webpy_app.utils import psa, backends from social.apps.webpy_app import app ...
class done(social_app.BaseViewClass): def GET(self): user = self.get_current_user() return render.done(user=user, backends=backends(user)) engine = create_engine('sqlite:///test.db', echo=True) def load_sqla(handler): web.ctx.orm = scoped_session(sessionmaker(bind=engine)) try: ...
def GET(self): return render.home()
identifier_body
app.py
import sys sys.path.append('../..') import web from web.contrib.template import render_jinja from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from social.utils import setting_name from social.apps.webpy_app.utils import psa, backends from social.apps.webpy_app import app ...
(self): return render.home() class done(social_app.BaseViewClass): def GET(self): user = self.get_current_user() return render.done(user=user, backends=backends(user)) engine = create_engine('sqlite:///test.db', echo=True) def load_sqla(handler): web.ctx.orm = scoped_session(sessio...
GET
identifier_name
app.py
import sys sys.path.append('../..') import web from web.contrib.template import render_jinja from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from social.utils import setting_name from social.apps.webpy_app.utils import psa, backends from social.apps.webpy_app import app ...
app.run()
conditional_block
app.py
import sys sys.path.append('../..') import web from web.contrib.template import render_jinja from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from social.utils import setting_name from social.apps.webpy_app.utils import psa, backends from social.apps.webpy_app import app ...
'social.backends.stripe.StripeOAuth2', 'social.backends.persona.PersonaAuth', 'social.backends.facebook.FacebookOAuth2', 'social.backends.facebook.FacebookAppOAuth2', 'social.backends.yahoo.YahooOAuth', 'social.backends.angel.AngelOAuth2', 'social.backends.behance.BehanceOAuth2', 'social...
'social.backends.google.GoogleOAuth2', 'social.backends.google.GoogleOAuth', 'social.backends.twitter.TwitterOAuth', 'social.backends.yahoo.YahooOpenId',
random_line_split