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
sparkline.rs
use std::fmt; pub struct Ascii { min: f64, max: f64, data: Vec<f64>, step: usize, } impl Ascii { pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self { Self { min, max, data, step, } } } impl fmt::Display for Ascii...
fn test_display() { let s = Ascii { min: 0., max: 1., data: vec![0.], step: 2, }; assert_eq!(format!("{}", s), "▁"); let s = Ascii { min: 0., max: 1., data: vec![0., 10.], step: 2, }; assert_eq!(format!("{}", s), "▁"); let s =...
{ let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇']; let ticks_len = (ticks.len() - 1) as f64; let sparkline: String = self .data .iter() .step_by(self.step) .map(|x| { let mut i = ticks_len * (x - self.min); if i ...
identifier_body
sparkline.rs
use std::fmt; pub struct Ascii { min: f64, max: f64, data: Vec<f64>, step: usize, } impl Ascii { pub fn
(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self { Self { min, max, data, step, } } } impl fmt::Display for Ascii { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇']; ...
new
identifier_name
overlaypanel.d.ts
import * as React from 'react'; import { CSSTransitionProps } from '../csstransition'; type OverlayPanelEventType = React.SyntheticEvent | undefined | null; type OverlayPanelTargetType = HTMLElement | EventTarget | undefined | null; type OverlayPanelAppendToType = 'self' | HTMLElement | undefined | null; interface ...
extends React.Component<OverlayPanelProps, any> { public toggle(event: OverlayPanelEventType, target?: OverlayPanelTargetType): void; public show(event: OverlayPanelEventType, target: OverlayPanelTargetType): void; public hide(): void; }
OverlayPanel
identifier_name
overlaypanel.d.ts
import * as React from 'react'; import { CSSTransitionProps } from '../csstransition'; type OverlayPanelEventType = React.SyntheticEvent | undefined | null; type OverlayPanelTargetType = HTMLElement | EventTarget | undefined | null; type OverlayPanelAppendToType = 'self' | HTMLElement | undefined | null; interface ...
public show(event: OverlayPanelEventType, target: OverlayPanelTargetType): void; public hide(): void; }
random_line_split
main.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. mod action; mod command; mod error; mod graphql; mod task; mod timer; use iml_manager_env::get_pool_limit; use iml_postgres::get_db_pool; use iml_rabbit::{self, creat...
let addr = iml_manager_env::get_iml_api_addr(); let conf = Conf { allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(), build: iml_manager_env::get_build(), version: iml_manager_env::get_version(), exa_version: iml_manager_env::get_exa_version(), is_release...
iml_tracing::init();
random_line_split
main.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. mod action; mod command; mod error; mod graphql; mod task; mod timer; use iml_manager_env::get_pool_limit; use iml_postgres::get_db_pool; use iml_rabbit::{self, creat...
let conn_filter = create_connection_filter(rabbit_pool); let pg_pool = get_db_pool(get_pool_limit().unwrap_or(DEFAULT_POOL_LIMIT)).await?; let pg_pool_2 = pg_pool.clone(); let db_pool_filter = warp::any().map(move || pg_pool.clone()); let schema = Arc::new(graphql::Schema::new( graphql::Qu...
{ iml_tracing::init(); let addr = iml_manager_env::get_iml_api_addr(); let conf = Conf { allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(), build: iml_manager_env::get_build(), version: iml_manager_env::get_version(), exa_version: iml_manager_env::get_exa_ve...
identifier_body
main.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. mod action; mod command; mod error; mod graphql; mod task; mod timer; use iml_manager_env::get_pool_limit; use iml_postgres::get_db_pool; use iml_rabbit::{self, creat...
() -> Result<(), Box<dyn std::error::Error>> { iml_tracing::init(); let addr = iml_manager_env::get_iml_api_addr(); let conf = Conf { allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(), build: iml_manager_env::get_build(), version: iml_manager_env::get_version(), ...
main
identifier_name
test_dics.py
_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj forward = mne.read_forward_solution(fname_fwd) if read_all_forward: forward_surf_ori = _read_forward_solution_meg(fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg(fname_fwd, forc...
noise_csds = data_csds with warnings.catch_warnings(record=True) as w: dics_source_power(epochs.info, forward, noise_csds, data_csds) assert_equal(len(w), 1) @testing.requires_testing_data def test_tf_dics(): """Test TF beamforming based on DICS
data_csd.frequencies = [freq]
conditional_block
test_dics.py
stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict...
"""Test TF beamforming based on DICS.""" tmin, tmax, tstep = -0.2, 0.2, 0.1 raw, epochs, _, _, _, label, forward, _, _, _ =\ _get_data(tmin, tmax, read_all_forward=False, compute_csds=False) freq_bins = [(4, 20), (30, 55)] win_lengths = [0.2, 0.2] reg = 0.05 noise_csds = [] for fre...
identifier_body
test_dics.py
_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj forward = mne.read_forward_solution(fname_fwd) if read_all_forward: forward_surf_ori = _read_forward_solution_meg(fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg(fname_fwd, forc...
(): """Test TF beamforming based on DICS
test_tf_dics
identifier_name
test_dics.py
(fname_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj forward = mne.read_forward_solution(fname_fwd) if read_all_forward: forward_surf_ori = _read_forward_solution_meg(fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg(fname_fwd...
# Test if fixed forward operator is detected when picking normal # orientation assert_raises(ValueError, dics_source_power, raw.info, forward_fixed, noise_csd, data_csd, pick_ori="normal") # Test if non-surface oriented forward operator is detected when picking # normal orientatio...
# orientation results assert_true((np.abs(stc_normal.data[:, 0]) <= stc_source_power.data[:, 0]).all())
random_line_split
toast.service.ts
import { Injectable } from '@angular/core'; // Services import { LogService, i18nService, ConfigService, SessionService, UploadService } from 'app/services'; import { ActionStatus } from 'app/enums'; @Injectable() export class ToastService {
(private translate: i18nService) { } public show(message: string, caption: string, status: ActionStatus, progress: boolean = false, timeout: number = 2000, position: string = 'toast-top-center') { (<any>window).toastr.options.timeOut = timeout; (<any>window).toastr.options.progressB...
constructor
identifier_name
toast.service.ts
import { Injectable } from '@angular/core'; // Services import { LogService, i18nService, ConfigService, SessionService, UploadService } from 'app/services'; import { ActionStatus } from 'app/enums'; @Injectable() export class ToastService { constructor(private translate: i18nService) { } public ...
}
break; } }
random_line_split
relocation.rs
use crate::error; use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith}; /// Size of a single COFF relocation. pub const COFF_RELOCATION_SIZE: usize = 10; // x86 relocations. /// The relocation is ignored. pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000;
/// Not supported. pub const IMAGE_REL_I386_REL16: u16 = 0x0002; /// The target's 32-bit VA. pub const IMAGE_REL_I386_DIR32: u16 = 0x0006; /// The target's 32-bit RVA. pub const IMAGE_REL_I386_DIR32NB: u16 = 0x0007; /// Not supported. pub const IMAGE_REL_I386_SEG12: u16 = 0x0009; /// The 16-bit section index of the sec...
/// Not supported. pub const IMAGE_REL_I386_DIR16: u16 = 0x0001;
random_line_split
relocation.rs
use crate::error; use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith}; /// Size of a single COFF relocation. pub const COFF_RELOCATION_SIZE: usize = 10; // x86 relocations. /// The relocation is ignored. pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000; /// Not supported. pub const IMAGE_REL_I386_DIR16: u16 = 0x00...
}
{ if self.offset >= self.relocations.len() { None } else { Some( self.relocations .gread_with(&mut self.offset, scroll::LE) .unwrap(), ) } }
identifier_body
relocation.rs
use crate::error; use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith}; /// Size of a single COFF relocation. pub const COFF_RELOCATION_SIZE: usize = 10; // x86 relocations. /// The relocation is ignored. pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000; /// Not supported. pub const IMAGE_REL_I386_DIR16: u16 = 0x00...
(&mut self) -> Option<Self::Item> { if self.offset >= self.relocations.len() { None } else { Some( self.relocations .gread_with(&mut self.offset, scroll::LE) .unwrap(), ) } } }
next
identifier_name
relocation.rs
use crate::error; use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith}; /// Size of a single COFF relocation. pub const COFF_RELOCATION_SIZE: usize = 10; // x86 relocations. /// The relocation is ignored. pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000; /// Not supported. pub const IMAGE_REL_I386_DIR16: u16 = 0x00...
else { Some( self.relocations .gread_with(&mut self.offset, scroll::LE) .unwrap(), ) } } }
{ None }
conditional_block
player.service.ts
import * as _ from 'lodash'; import { Observable } from 'rxjs'; import { createSelector } from 'reselect'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Subject } from 'rxjs/Subject'; import { AppState } from '../../../common/app.reducer'; import { Note } from '../../../com...
} notesAt(beat: number, tick: number): Note[] { return _.filter(_.map(_.values(this._data), (data: Surface.Data[]) => data[beat].noteAt(tick))); } }
{ let [beat, pulse] = surface.beatPulseFor(cursor); let data = surface.dataFor(beat, this._data); return data.notes[pulse] === surface.soundByKey[key]; }
conditional_block
player.service.ts
import * as _ from 'lodash'; import { Observable } from 'rxjs'; import { createSelector } from 'reselect'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Subject } from 'rxjs/Subject'; import { AppState } from '../../../common/app.reducer'; import { Note } from '../../../com...
} notesAt(beat: number, tick: number): Note[] { return _.filter(_.map(_.values(this._data), (data: Surface.Data[]) => data[beat].noteAt(tick))); } }
if (surface instanceof A1Grid) { let [beat, pulse] = surface.beatPulseFor(cursor); let data = surface.dataFor(beat, this._data); return data.notes[pulse] === surface.soundByKey[key]; }
random_line_split
player.service.ts
import * as _ from 'lodash'; import { Observable } from 'rxjs'; import { createSelector } from 'reselect'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Subject } from 'rxjs/Subject'; import { AppState } from '../../../common/app.reducer'; import { Note } from '../../../com...
set(key: string, cursor: number) { let surface = this.lesson.surfaceFor(key); if (surface) { this.store.dispatch(new Player.SetAction({ key, surface, cursor })); } return !!surface; } unset(key: string, cursor: number) { let surface = this.lesson.surfaceFor(key); if (surface) { ...
{ this.store.dispatch(new Player.UnselectAction()); }
identifier_body
player.service.ts
import * as _ from 'lodash'; import { Observable } from 'rxjs'; import { createSelector } from 'reselect'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Subject } from 'rxjs/Subject'; import { AppState } from '../../../common/app.reducer'; import { Note } from '../../../com...
(key: string, cursor?: number) { let surface = this.lesson.surfaceFor(key); if (surface) { this.store.dispatch(new Player.SelectAction({ key, surface, cursor })); } } unselect() { this.store.dispatch(new Player.UnselectAction()); } set(key: string, cursor: number) { let surface = thi...
select
identifier_name
match.py
#! /usr/bin/env python # -*- coding: utf-8 -*- def replace_attr_if_match(mapper, dic): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] dic : sorted list [(key, value)] Returns ------- dic : dict dict mapped by mapper. Examples -------- >>> d...
elif x < y: return -1 else: return 0
return 1
conditional_block
match.py
#! /usr/bin/env python # -*- coding: utf-8 -*- def replace_attr_if_match(mapper, dic):
>>> 'key1': [('pattern1_1', 'value1'), ('pattern1_2', 'value2')], >>> 'key2': [('pattern2_1', 'value1')], >>> 'key3': [('pattern3_1', 'value1')], >>> } >>> result = replace_attr_if_match(mapper, dict_1) >>> result {'key1': 'value2', 'key2': 'value1', 'key3': 'pattern3_3', 'ke...
""" Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] dic : sorted list [(key, value)] Returns ------- dic : dict dict mapped by mapper. Examples -------- >>> dict_1 = { >>> 'key1': 'pattern1_2', >>> 'key2': 'pattern2_1', >>> 'ke...
identifier_body
match.py
#! /usr/bin/env python # -*- coding: utf-8 -*- def replace_attr_if_match(mapper, dic): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] dic : sorted list [(key, value)] Returns ------- dic : dict dict mapped by mapper. Examples -------- >>> d...
(mapper, xs, res): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] xs : sorted list [(key, value)] res : list of (key, value) tuples Returns ------- res : list of (key, value) tuples """ if not mapper or not xs: return res + xs else: ...
__match_map
identifier_name
match.py
#! /usr/bin/env python # -*- coding: utf-8 -*- def replace_attr_if_match(mapper, dic): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] dic : sorted list [(key, value)] Returns ------- dic : dict dict mapped by mapper. Examples -------- >>> d...
return dict(res) def replace_if_match(xs, y): """ Find the first pattern match in list. Return the corresponding value of patterns if matches, return the same value of x if there has no match. Parameters ---------- xs : [(pattern, value)] y : object Returns ------- re...
sorted_mapper = sorted(mapper.items()) sorted_dic = sorted(dic.items()) res = __match_map(sorted_mapper, sorted_dic, [])
random_line_split
post_message_shim.js
// Set up a bridge between Model-R and postmessage. // // The convention is that everything sent via post-message is a JSON-encoded object with a // field called "action" which is used to determine which message was sent. // // So, if we receive '{"action":"complete","status":200}' from the iframe, // that will get con...
if (opts.model) { lib.model(_public, _protected, opts.model); opts.receive = (opts.receive || []).concat(_(opts.model).map(function (field) { return field + '_sync'; })); _(opts.model).each(function (name) { var syncedValue; _public.on(name + '...
{ if (debug) { console.log((opts.name || 'pmshim') + " SENT-->: " + JSON.stringify(msg)); } $.message(other, msg, (_.isFunction(opts.remote_base_url) ? opts.remote_base_url() : opts.remote_base_url)); }
identifier_body
post_message_shim.js
// Set up a bridge between Model-R and postmessage. // // The convention is that everything sent via post-message is a JSON-encoded object with a // field called "action" which is used to determine which message was sent. // // So, if we receive '{"action":"complete","status":200}' from the iframe, // that will get con...
// send: [a list of actions we expect to send], // model: [a list of fields to copy around amoungst the frames] // remote_base_url: the url to send with postMessage to ensure it arrives at the correct domain // } // // remote_base_url can be a function, in which case it is evaluated every time a message is sent. ...
random_line_split
post_message_shim.js
// Set up a bridge between Model-R and postmessage. // // The convention is that everything sent via post-message is a JSON-encoded object with a // field called "action" which is used to determine which message was sent. // // So, if we receive '{"action":"complete","status":200}' from the iframe, // that will get con...
$.message(other, msg, (_.isFunction(opts.remote_base_url) ? opts.remote_base_url() : opts.remote_base_url)); } if (opts.model) { lib.model(_public, _protected, opts.model); opts.receive = (opts.receive || []).concat(_(opts.model).map(function (field) { return field + '_syn...
{ console.log((opts.name || 'pmshim') + " SENT-->: " + JSON.stringify(msg)); }
conditional_block
post_message_shim.js
// Set up a bridge between Model-R and postmessage. // // The convention is that everything sent via post-message is a JSON-encoded object with a // field called "action" which is used to determine which message was sent. // // So, if we receive '{"action":"complete","status":200}' from the iframe, // that will get con...
(msg) { if (debug) { console.log((opts.name || 'pmshim') + " SENT-->: " + JSON.stringify(msg)); } $.message(other, msg, (_.isFunction(opts.remote_base_url) ? opts.remote_base_url() : opts.remote_base_url)); } if (opts.model) { lib.model(_public, _protected, opts.mode...
sendMessage
identifier_name
AddTag.js
/* @flow */ import React from 'react'; import { Field, reduxForm } from 'redux-form'; import { graphql, compose } from 'react-apollo'; import styled from 'styled-components'; // internal import Button from '@boldr/ui/Button'; import Heading from '@boldr/ui/Heading'; import { Control, FormField, Form, TextFormField } fr...
pristine?: boolean, }; const style = { margin: 12, }; const TagFormPanel = styled.div` padding: 2em; margin: 0 auto; `; class AddTag extends React.Component<Props, *> { addTagMutation = values => { const { addTagMutation } = this.props; return addTagMutation(values).catch(formatReduxFormErrors); ...
addTagMutation: Function, handleSubmit: Function, reset?: Function, submitting?: boolean,
random_line_split
VeehdCom.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster class VeehdCom(Hoster): __name__ = 'VeehdCom' __type__ = 'hoster' __pattern__ = r'http://veehd\.com/video/\d+_\S+' __config__ = [ ('filename_spaces', 'bool', "Allow spaces in filename", 'False'), ...
(self): self.html = None self.multiDL = True self.req.canContinue = True def process(self, pyfile): self.download_html() if not self.file_exists(): self.offline() pyfile.name = self.get_file_name() self.download(self.get_file_url()) def down...
setup
identifier_name
VeehdCom.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster class VeehdCom(Hoster): __name__ = 'VeehdCom' __type__ = 'hoster' __pattern__ = r'http://veehd\.com/video/\d+_\S+' __config__ = [ ('filename_spaces', 'bool', "Allow spaces in filename", 'False'), ...
else: pattern = '[^0-9A-Za-z\.]+' name = re.sub(pattern, self.getConfig('replacement_char'), name) return name + '.avi' def get_file_url(self): """ returns the absolute downloadable filepath """ if self.html is None: se...
pattern = '[^0-9A-Za-z\.\ ]+'
conditional_block
VeehdCom.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster class VeehdCom(Hoster): __name__ = 'VeehdCom' __type__ = 'hoster' __pattern__ = r'http://veehd\.com/video/\d+_\S+' __config__ = [ ('filename_spaces', 'bool', "Allow spaces in filename", 'False'), ...
def file_exists(self): if self.html is None: self.download_html() if '<title>Veehd</title>' in self.html: return False return True def get_file_name(self): if self.html is None: self.download_html() match = re.search(r'<title[^>]*>...
url = self.pyfile.url self._debug("Requesting page: %s" % (repr(url),)) self.html = self.load(url)
identifier_body
VeehdCom.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster class VeehdCom(Hoster): __name__ = 'VeehdCom'
] __version__ = '0.23' __description__ = """Veehd.com Download Hoster""" __author_name__ = ('cat') __author_mail__ = ('cat@pyload') def _debug(self, msg): self.logDebug('[%s] %s' % (self.__name__, msg)) def setup(self): self.html = None self.multiDL = True s...
__type__ = 'hoster' __pattern__ = r'http://veehd\.com/video/\d+_\S+' __config__ = [ ('filename_spaces', 'bool', "Allow spaces in filename", 'False'), ('replacement_char', 'str', "Filename replacement character", '_'),
random_line_split
main.rs
extern crate rand; use std::io; use std::io::Write; use std::cmp::Ordering; use rand::Rng; fn main()
Ordering::Less => { println!("{} ist zu klein, versuch's nochmal!\n", guess); }, Ordering::Greater => { println!("{} ist zu gross, versuch's nochmal!\n", guess); }, Ordering::Equal => { println!("----------------...
{ println!("Zahlenraten!"); println!("============"); let secret = rand::thread_rng().gen_range(1, 101); //println!("Die Geheimzahl lautet: {}", secret); loop { print!("Geheimzahl eingeben (< 100): "); io::stdout().flush().ok().expect("Konnte stdout nicht flushen."); let mu...
identifier_body
main.rs
extern crate rand; use std::io; use std::io::Write; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Zahlenraten!"); println!("============"); let secret = rand::thread_rng().gen_range(1, 101); //println!("Die Geheimzahl lautet: {}", secret); loop { print!("Geheimzahl eingeb...
, Ordering::Greater => { println!("{} ist zu gross, versuch's nochmal!\n", guess); }, Ordering::Equal => { println!("-------------------"); println!("\\o/ Gewonnen! \\o/"); println!("-------------------"); ...
{ println!("{} ist zu klein, versuch's nochmal!\n", guess); }
conditional_block
main.rs
extern crate rand; use std::io; use std::io::Write; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Zahlenraten!"); println!("============"); let secret = rand::thread_rng().gen_range(1, 101); //println!("Die Geheimzahl lautet: {}", secret); loop { print!("Geheimzahl eingeb...
println!("-------------------"); break; }, } } }
println!("-------------------"); println!("\\o/ Gewonnen! \\o/");
random_line_split
main.rs
extern crate rand; use std::io; use std::io::Write; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Zahlenraten!"); println!("============"); let secret = rand::thread_rng().gen_range(1, 101); //println!("Die Geheimzahl lautet: {}", secret); loop { print!("Geheimzahl eingeben (< 100): "); io::stdout().flush().ok().expect("Konnte stdout nicht flushen."); let...
main
identifier_name
autoderef-method-twice.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self: Box<usize>) -> usize { *self * 2 } } pub fn main() { let x: Box<Box<_>> = box box 3; assert_eq!(x.double(), 6); }
double
identifier_name
autoderef-method-twice.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x: Box<Box<_>> = box box 3; assert_eq!(x.double(), 6); }
identifier_body
post.component.ts
import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core'; import { CollectionService } from "../service.service"; @Component({ selector: 'app-post', providers: [CollectionService], templateUrl: './post.component.html', styleUrls: ['./post.component.scss'], encapsulation:...
{ @Input() post; @Input() index; @Output() deleted = new EventEmitter(); @Output() created = new EventEmitter(); service:CollectionService; edit = false; backupcopy = ""; constructor(service:CollectionService) { this.service = service; } deletePost() { if (confirm("Delete Pos...
PostComponent
identifier_name
post.component.ts
import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core'; import { CollectionService } from "../service.service"; @Component({ selector: 'app-post', providers: [CollectionService], templateUrl: './post.component.html', styleUrls: ['./post.component.scss'], encapsulation:...
}
{ this.post = {"attributes":{}}; }
identifier_body
post.component.ts
import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core'; import { CollectionService } from "../service.service"; @Component({ selector: 'app-post', providers: [CollectionService], templateUrl: './post.component.html', styleUrls: ['./post.component.scss'], encapsulation:...
}
random_line_split
post.component.ts
import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core'; import { CollectionService } from "../service.service"; @Component({ selector: 'app-post', providers: [CollectionService], templateUrl: './post.component.html', styleUrls: ['./post.component.scss'], encapsulation:...
} editPost() { this.backupcopy = JSON.stringify(this.post); this.edit = true; } cancelEdit() { this.post = JSON.parse(this.backupcopy); this.backupcopy = ""; this.edit = false; } savePost() { this.service.saveRecord(this.post.id, this.post) .subscribe(() =...
{ this.service.deleteRecord(this.post.id) .subscribe(() => this.deleted.emit("deleted")); }
conditional_block
reach_reader.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging from indra.java_vm import autoclass, JavaException logger = logging.getLogger('reach_reader') class ReachReader(object): """The ReachReader wraps a singleton instance of the REACH reader. Th...
# This second autoclass is needed because of a jnius # issue in which the first JavaException is not raised. try: autoclass('java.lang.String') except JavaException as e: logger.error(e) pass ...
if self.api_ruler is None: try: self.api_ruler = \ autoclass('org.clulab.reach.export.apis.ApiRuler') except JavaException:
random_line_split
reach_reader.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging from indra.java_vm import autoclass, JavaException logger = logging.getLogger('reach_reader') class ReachReader(object): """The ReachReader wraps a singleton instance of the REACH reader. Th...
(self): """Return the existing reader if it exists or launch a new one. Returns ------- api_ruler : org.clulab.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """ if self.api_ruler is None: try: self.api_...
get_api_ruler
identifier_name
reach_reader.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging from indra.java_vm import autoclass, JavaException logger = logging.getLogger('reach_reader') class ReachReader(object): """The ReachReader wraps a singleton instance of the REACH reader. Th...
return self.api_ruler
try: self.api_ruler = \ autoclass('org.clulab.reach.export.apis.ApiRuler') except JavaException: # This second autoclass is needed because of a jnius # issue in which the first JavaException is not raised. try: ...
conditional_block
reach_reader.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging from indra.java_vm import autoclass, JavaException logger = logging.getLogger('reach_reader') class ReachReader(object): """The ReachReader wraps a singleton instance of the REACH reader. Th...
return self.api_ruler
"""Return the existing reader if it exists or launch a new one. Returns ------- api_ruler : org.clulab.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """ if self.api_ruler is None: try: self.api_ruler = \ ...
identifier_body
range.py
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of...
(self, k): """Return entry at index k (using standard interpretation if negative).""" if k < 0: k += len(self) # attempt to convert negative index if not 0 <= k < self._length: raise IndexError('index out of range') return self._start + k * self...
__getitem__
identifier_name
range.py
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of...
return self._start + k * self._step
raise IndexError('index out of range')
conditional_block
range.py
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of...
def __len__(self): """Return number of entries in the range.""" return self._length def __getitem__(self, k): """Return entry at index k (using standard interpretation if negative).""" if k < 0: k += len(self) # attempt to convert negative index ...
"""A class that mimic's the built-in range class.""" def __init__(self, start, stop=None, step=1): """Initialize a Range instance. Semantics is similar to built-in range class. """ if step == 0: raise ValueError('step cannot be 0') if stop is None: ...
identifier_body
range.py
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # alon...
# 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.
random_line_split
GbtBoardFormat.ts
/// <reference path="../IBoard.ts" /> /// <reference path="../../utilities/String.ts" /> /// <reference path="../../utilities/Functional.ts" /> /// <reference path="./IBoardFormat.ts" /> /* Partially transcribed from PyGobstones */ class
implements IBoardFormat { cellWidth:number cellHeight:number maxNumberLength:number constructor(cellWidth:number=9, cellHeight:number=3, maxNumberLength:number=3) { this.cellWidth = cellWidth this.cellHeight = cellHeight this.maxNumberLength = maxNumberLength } load(board:IBoard, s:string) { throw ...
GbtBoardFormat
identifier_name
GbtBoardFormat.ts
/// <reference path="../IBoard.ts" /> /// <reference path="../../utilities/String.ts" /> /// <reference path="../../utilities/Functional.ts" /> /// <reference path="./IBoardFormat.ts" /> /* Partially transcribed from PyGobstones */ class GbtBoardFormat implements IBoardFormat { cellWidth:number cellHeight:number ...
numbered_contents(board:IBoard):Array<string> { var res:Array<string> = new Array<string>() var out:any = this.board_contents(board) // vertical numbers var row_id:number = board.getSize().height var i:number = 0 foreach(out, (row:Array<any>)=> { if (i % (this.cellHeight + 1...
return output }
random_line_split
GbtBoardFormat.ts
/// <reference path="../IBoard.ts" /> /// <reference path="../../utilities/String.ts" /> /// <reference path="../../utilities/Functional.ts" /> /// <reference path="./IBoardFormat.ts" /> /* Partially transcribed from PyGobstones */ class GbtBoardFormat implements IBoardFormat { cellWidth:number cellHeight:number ...
load(board:IBoard, s:string) { throw new Error("Not implemented") } dump(board:IBoard):string { var output:string = "" var rows:Array<string> = this.numbered_contents(board) var i:number = 0 var sep:string foreach(rows,(row:string) => { if (i == rows.length - 1) { sep = '' ...
{ this.cellWidth = cellWidth this.cellHeight = cellHeight this.maxNumberLength = maxNumberLength }
identifier_body
aarch64_unknown_netbsd.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> TargetResult { let mut base = super::netbsd_base::opts(); base.max_atomic_width = Some(128); base.abi_blacklist = super::arm_base::abi_blacklist(); Ok(Target { llvm_target: "aarch64-unknown-netbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64...
target
identifier_name
aarch64_unknown_netbsd.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let mut base = super::netbsd_base::opts(); base.max_atomic_width = Some(128); base.abi_blacklist = super::arm_base::abi_blacklist(); Ok(Target { llvm_target: "aarch64-unknown-netbsd".to_string(), target_endian: "little".to_string(), target_pointer_width: "64".to_string(), ...
identifier_body
aarch64_unknown_netbsd.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.max_atomic_width = Some(128); base.abi_blacklist = super::arm_base::abi_blacklist(); Ok(Target { llvm_target: "aarch64-unknown-netbsd".to_string(), target_endian: "little".to_string(), target_point...
use spec::{LinkerFlavor, Target, TargetResult};
random_line_split
frame.js
import m from 'mithril'; export function view(ctrl, Body)
{ return <html> <head> <title>readings</title> <meta charset="utf-8" /> <meta name="description" content="A platform to present written information about specific topics" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//fonts.googleapis.com/icon?...
identifier_body
frame.js
import m from 'mithril'; export function view(ctrl, Body) { return <html> <head> <title>readings</title> <meta charset="utf-8" /> <meta name="description" content="A platform to present written information about specific topics" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> ...
}
random_line_split
frame.js
import m from 'mithril'; export function
(ctrl, Body) { return <html> <head> <title>readings</title> <meta charset="utf-8" /> <meta name="description" content="A platform to present written information about specific topics" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//fonts.googlea...
view
identifier_name
base.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
(): config = [ get_listen_config( is_proxy=False, port=settings.PROXIES_CONFIG.streams_target_port ) ] config += [ get_logging_config(), get_gzip_config(), get_charset_config(), get_buffering_config(), get_timeout_config(), get_guni...
get_base_config
identifier_name
base.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
config = [ get_listen_config( is_proxy=False, port=settings.PROXIES_CONFIG.streams_target_port ) ] config += [ get_logging_config(), get_gzip_config(), get_charset_config(), get_buffering_config(), get_timeout_config(), get_gunicorn_con...
identifier_body
base.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIE...
random_line_split
comment_eater.py
from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import compiler import inspect import textwrap import tokenize from .compiler_unparse import unparse class Comment(object): """ A comment block....
block = self.index.get(lineno, None) text = getattr(block, 'text', default) return text def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = ...
self.make_index()
conditional_block
comment_eater.py
from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import compiler import inspect import textwrap import tokenize from .compiler_unparse import unparse class Comment(object): """ A comment block....
(object): """ Pull out contiguous comment blocks. """ def __init__(self): # Start with a dummy. self.current_block = NonComment(0, 0) # All of the blocks seen so far. self.blocks = [] # The index mapping lines of code to their associated comment blocks. self...
CommentBlocker
identifier_name
comment_eater.py
from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import compiler import inspect import textwrap import tokenize from .compiler_unparse import unparse class Comment(object): """ A comment block....
def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) ...
""" Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text
identifier_body
comment_eater.py
from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import compiler import inspect import textwrap import tokenize from .compiler_unparse import unparse
is_comment = True def __init__(self, start_lineno, end_lineno, text): # int : The first line number in the block. 1-indexed. self.start_lineno = start_lineno # int : The last line number. Inclusive! self.end_lineno = end_lineno # str : The text block including '#' charact...
class Comment(object): """ A comment block. """
random_line_split
debug_meta.py
from __future__ import absolute_import __all__ = ("DebugMeta",) from sentry.interfaces.base import Interface from sentry.utils.json import prune_empty_keys class DebugMeta(Interface): """ Holds debug meta information for processing stacktraces and similar things. This information is deleted after event...
return prune_empty_keys( { "images": self.images or None, "sdk_info": self.sdk_info or None, "is_debug_build": self.is_debug_build, } )
identifier_body
debug_meta.py
from __future__ import absolute_import __all__ = ("DebugMeta",) from sentry.interfaces.base import Interface from sentry.utils.json import prune_empty_keys class DebugMeta(Interface): """ Holds debug meta information for processing stacktraces and similar things. This information is deleted after event...
(self): return prune_empty_keys( { "images": self.images or None, "sdk_info": self.sdk_info or None, "is_debug_build": self.is_debug_build, } )
to_json
identifier_name
debug_meta.py
from __future__ import absolute_import __all__ = ("DebugMeta",) from sentry.interfaces.base import Interface from sentry.utils.json import prune_empty_keys class DebugMeta(Interface): """ Holds debug meta information for processing stacktraces and similar things. This information is deleted after event...
images=data.get("images", None) or [], sdk_info=data.get("sdk_info"), is_debug_build=data.get("is_debug_build"), ) def to_json(self): return prune_empty_keys( { "images": self.images or None, "sdk_info": self.sdk_info o...
@classmethod def to_python(cls, data): return cls(
random_line_split
shim-plugin.js
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('shim-plugin', function (Y, NAME) { /** * Provides shimming support for Node via a Plugin. * This fixes SELECT bleedthrough for IE6 & Mac scr...
}, /** * Removes the shim and destroys the plugin * @method destroy */ destroy: function() { var shim = this._shim; if (shim) { shim.remove(true); } this._resizeHandle.detach(); } ...
{ shim.setAttrs({ width: node.getStyle('width'), height: node.getStyle('height') }); }
conditional_block
shim-plugin.js
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('shim-plugin', function (Y, NAME) { /** * Provides shimming support for Node via a Plugin. * This fixes SELECT bleedthrough for IE6 & Mac scr...
(config) { this.init(config); } /** * Default class used to mark the shim element * * @property CLASS_NAME * @type String * @static * @default "yui-node-shim" */ // TODO: use ClassNameManager Shim.CLASS_NAME = 'yui-node-shim'; /** * D...
Shim
identifier_name
shim-plugin.js
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('shim-plugin', function (Y, NAME) { /** * Provides shimming support for Node via a Plugin. * This fixes SELECT bleedthrough for IE6 & Mac scr...
/** * Default class used to mark the shim element * * @property CLASS_NAME * @type String * @static * @default "yui-node-shim" */ // TODO: use ClassNameManager Shim.CLASS_NAME = 'yui-node-shim'; /** * Default markup template used to generate the s...
{ this.init(config); }
identifier_body
shim-plugin.js
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('shim-plugin', function (Y, NAME) {
/** * Provides shimming support for Node via a Plugin. * This fixes SELECT bleedthrough for IE6 & Mac scrollbars * @module shim-plugin */ /** * Node plugin which can be used to add shim support. * * @class Plugin.Shim * @param {Object} User configuration obje...
random_line_split
conf.py
# -*- coding: utf-8 -*- # # Zend Framework 2 documentation build configuration file, created by # sphinx-quickstart on Fri Jul 6 18:55:07 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
# Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #h...
# typographically correct entities. #html_use_smartypants = True
random_line_split
test_request_queue.py
from functools import partial from time import sleep from mock import call, Mock from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import log, signals from scrapy.settings import Settings from scrapy.spider import BaseSpider from scrapy.xlib.pydispatch import dispatcher from twisted.intern...
reactor.stop() def _wait(self, url, *args, **kwargs): sleep(0.1) def test_priorization(self): webdriver = Mock() settings = self.settings(WEBDRIVER_BROWSER=webdriver) webdriver.get.side_effect = self._wait webdriver.page_source = u'' dispatcher.connect(...
def _stop_reactor(self):
random_line_split
test_request_queue.py
from functools import partial from time import sleep from mock import call, Mock from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import log, signals from scrapy.settings import Settings from scrapy.spider import BaseSpider from scrapy.xlib.pydispatch import dispatcher from twisted.intern...
(self, **options): settings = self._settings.copy() settings.update(**options) return settings def _stop_reactor(self): reactor.stop() def _wait(self, url, *args, **kwargs): sleep(0.1) def test_priorization(self): webdriver = Mock() settings = self....
settings
identifier_name
test_request_queue.py
from functools import partial from time import sleep from mock import call, Mock from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import log, signals from scrapy.settings import Settings from scrapy.spider import BaseSpider from scrapy.xlib.pydispatch import dispatcher from twisted.intern...
def parse_action(self, response): yield WebdriverRequest('%s&wr=%d' % (response.url, 0), callback=self.parse_nothing) def parse_nothing(self, response): pass
fake_url = '%s&wa=%d' % (response.url, i) request = response.action_request(url=fake_url, callback=self.parse_action) # Leave a trace in the webdriver instance mock so we can look # at the request processing order. ...
conditional_block
test_request_queue.py
from functools import partial from time import sleep from mock import call, Mock from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import log, signals from scrapy.settings import Settings from scrapy.spider import BaseSpider from scrapy.xlib.pydispatch import dispatcher from twisted.intern...
def _stop_reactor(self): reactor.stop() def _wait(self, url, *args, **kwargs): sleep(0.1) def test_priorization(self): webdriver = Mock() settings = self.settings(WEBDRIVER_BROWSER=webdriver) webdriver.get.side_effect = self._wait webdriver.page_source = u...
settings = self._settings.copy() settings.update(**options) return settings
identifier_body
running-with-no-runtime.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 ...
#[start] fn start(argc: isize, argv: *const *const u8) -> isize { if argc > 1 { unsafe { match **argv.offset(1) as char { '1' => {} '2' => println!("foo"), '3' => assert!(thread::catch_panic(|| {}).is_ok()), '4' => assert!(thread::c...
use std::thread; use std::str;
random_line_split
running-with-no-runtime.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 ...
}; let me = String::from_utf8(args[0].to_vec()).unwrap(); pass(Command::new(&me).arg("1").output().unwrap()); pass(Command::new(&me).arg("2").output().unwrap()); pass(Command::new(&me).arg("3").output().unwrap()); pass(Command::new(&me).arg("4").output().unwrap()); pass(Command::new(&me).ar...
{ if argc > 1 { unsafe { match **argv.offset(1) as char { '1' => {} '2' => println!("foo"), '3' => assert!(thread::catch_panic(|| {}).is_ok()), '4' => assert!(thread::catch_panic(|| panic!()).is_err()), '5' => assert...
identifier_body
running-with-no-runtime.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 ...
(output: Output) { if !output.status.success() { println!("{:?}", str::from_utf8(&output.stdout)); println!("{:?}", str::from_utf8(&output.stderr)); } }
pass
identifier_name
plotting_tools.py
# Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the fol...
else: pred = misc.imread(file_tuple[2]) if pred.shape[0] != im.shape[0]: mask = misc.imresize(mask, pred.shape) im = misc.imresize(im, pred.shape) return im, mask, pred def plot_keras_model(model, fig_name): base_path = os.path.join('..', 'data', 'figures') ...
return im, mask
conditional_block
plotting_tools.py
# Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the fol...
def train_val_curve(train_loss, val_loss=None): train_line = plt.plot(train_loss, label='train_loss') train_patch = mpatches.Patch(color='blue',label='train_loss') handles = [train_patch] if val_loss: val_line = plt.plot(val_loss, label='val_loss') val_patch = mpatches.Patch(color='or...
base_path = os.path.join('..', 'data', 'figures') make_dir_if_not_exist(base_path) keras.utils.vis_utils.plot_model(model, os.path.join(base_path, fig_name)) keras.utils.vis_utils.plot_model(model, os.path.join(base_path, fig_name +'_with_shapes'), show_shapes=True)
identifier_body
plotting_tools.py
# Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the fol...
(self, batch, logs=None): logs = logs or {} batch_size = logs.get('size', 0) self.seen += batch_size for k, v in logs.items(): if k in self.totals: self.totals[k] += v * batch_size else: self.totals[k] = v * batch_size ...
on_batch_end
identifier_name
plotting_tools.py
# Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the fol...
def load_images(file_tuple): im = misc.imread(file_tuple[0]) mask = misc.imread(file_tuple[1]) if len(file_tuple) == 2: return im, mask else: pred = misc.imread(file_tuple[2]) if pred.shape[0] != im.shape[0]: mask = misc.imresize(mask, pred.shape) im = mis...
random_line_split
urls.py
from server.rides.views import RidesList, RideDetails, RideRidersList, RideRiderDetails, RideRiderCharge, RideRiderFundraiser urlpatterns = [ url(r'^(?P<id>\d+)/riders/(?P<rider_id>\d+)/fundraiser', RideRiderFundraiser.as_view(), name='ride-rider-fundraiser'), url(r'^(?P<id>\d+)/riders/(?P<rider_id>\d+)/charg...
from django.conf.urls import url, include
random_line_split
ws.ts
import { ColumnDefinition, Post, PostGroup, SessionOptions, User, VoteExtract, VoteType, } from './types'; export interface WebsocketMessage<T> { payload: T; sessionId: string; ack: string; } export interface WsUserData { user: User; } export interface WsNameData { name: string; } export int...
} export interface WsDeletePostPayload { postId: string; } export interface WsDeleteGroupPayload { groupId: string; } export interface WsSaveTemplatePayload { columns: ColumnDefinition[]; options: SessionOptions; } export interface WsUserReadyPayload { userId: string; ready: boolean; name: string; } ...
export interface WsReceiveLikeUpdatePayload { postId: string; vote: VoteExtract;
random_line_split
raphael-map.ts
 angular.module('app.raphael').directive('raphaelMap', [ 'raphaelMaps', 'raphaelMapCreator', 'raphaelColorScale', ( raphaelMaps: any, raphaelMapCreator: app.raphael.RaphaelMapCreator, raphaelColorScaleFactory: app.raphael.IRaphaelColorScaleFactory) => { return { scope:...
path.attr({ 'fill': '#009688' }); (function (hPath) { hPath.hover(function () { if (!hPath.isClicked) { hPath.attr({ "stroke": '#FFEB3B', 'stroke-width': '2', 'cursor': 'pointer' }); ...
}
conditional_block
raphael-map.ts
 angular.module('app.raphael').directive('raphaelMap', [ 'raphaelMaps', 'raphaelMapCreator', 'raphaelColorScale', ( raphaelMaps: any, raphaelMapCreator: app.raphael.RaphaelMapCreator, raphaelColorScaleFactory: app.raphael.IRaphaelColorScaleFactory) => { return { scope:...
{ return raphaelMapCreator.CreateMap(element[0]); } var map = _.find(raphaelMaps, (b: any) => { return b.name === 'Region2007'; }); buildMap(); var pathGroup = map.func(raphaelMapCreator.paper, { ...
ildMap()
identifier_name
raphael-map.ts
 angular.module('app.raphael').directive('raphaelMap', [ 'raphaelMaps', 'raphaelMapCreator', 'raphaelColorScale', ( raphaelMaps: any, raphaelMapCreator: app.raphael.RaphaelMapCreator, raphaelColorScaleFactory: app.raphael.IRaphaelColorScaleFactory) => { return { scope:...
}, function () { if (!hPath.isClicked) { hPath.attr({ "stroke": "none" }); } } ); } (path))...
random_line_split
raphael-map.ts
 angular.module('app.raphael').directive('raphaelMap', [ 'raphaelMaps', 'raphaelMapCreator', 'raphaelColorScale', ( raphaelMaps: any, raphaelMapCreator: app.raphael.RaphaelMapCreator, raphaelColorScaleFactory: app.raphael.IRaphaelColorScaleFactory) => { return { scope:...
var map = _.find(raphaelMaps, (b: any) => { return b.name === 'Region2007'; }); buildMap(); var pathGroup = map.func(raphaelMapCreator.paper, { defaultFillColor: '#bbc8d5' }); var co...
return raphaelMapCreator.CreateMap(element[0]); }
identifier_body
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
random_line_split
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Drop for Socket { fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } } }
{ Socket { fd: fd } }
identifier_body
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self) -> TcpStream { unsafe { TcpStream::from_raw_fd(self.into_fd()) } } pub fn into_udp_socket(self) -> UdpSocket { unsafe { UdpSocket::from_raw_fd(self.into_fd()) } } } impl ::FromInner for Socket { type Inner = c_int; fn from_inner(fd: c_int) -> Socket { Socket { fd: fd...
into_tcp_stream
identifier_name
test_static_webgl_library.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 u...
try_static_webgl_library()
conditional_block
test_static_webgl_library.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 u...
"-s", "USE_GLFW=3", "-s", "USE_WEBGL2=1", "-lglfw", ]) # Create "tvm_runtime.js" and "identity_static.html" in lib/ shutil.copyfile(os.path.join(curr_path, "../../web/tvm_runtime.js"), "tvm_runtime.js") shutil.copyfile(os.path.join(curr_path, "test_static_web...
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) # Change to lib/ which contains "libtvm_runtime.bc". os.chdir(os.path.join(curr_path, "../../lib")) # Create OpenGL module. n = tvm.var("n") A = tvm.placeholder((n,), name='A', dtype="float") B = tvm.compute((n,), lambd...
identifier_body
test_static_webgl_library.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 u...
f.export_library(path_dso, emscripten.create_js, options=[ "-s", "USE_GLFW=3", "-s", "USE_WEBGL2=1", "-lglfw", ]) # Create "tvm_runtime.js" and "identity_static.html" in lib/ shutil.copyfile(os.path.join(curr_path, "../../web/tvm_runtime.js"), "tvm_runtime.js...
# Create a JS library that contains both the module and the tvm runtime. path_dso = "identity_static.js"
random_line_split
test_static_webgl_library.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 u...
(): curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) # Change to lib/ which contains "libtvm_runtime.bc". os.chdir(os.path.join(curr_path, "../../lib")) # Create OpenGL module. n = tvm.var("n") A = tvm.placeholder((n,), name='A', dtype="float") B = tvm.compute((n,...
try_static_webgl_library
identifier_name