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
eda.py
text_to_wordlist( review, remove_stopwords=False ): # Function to convert a document to a sequence of words, # optionally removing stop words. Returns a list of words. # # 1. Remove HTML text = BeautifulSoup(review,'html.parser').get_text() # # 2. Remove non-letters text = re.sub("[^A-...
raise ValueError('TODO: ' + model)
conditional_block
eda.py
(TfidfVectorizer, self).build_analyzer() return lambda doc: english_stemmer.stemWords(analyzer(doc)) def text_to_wordlist( review, remove_stopwords=False ): # Function to convert a document to a sequence of words, # optionally removing stop words. Returns a list of words. # # 1. Remove HTML ...
words = text.lower().split() # # 4. Optionally remove stop words (false by default) if remove_stopwords: stops = set(stopwords.words("english")) words = [w for w in words if not w in stops] # 5. Return a list return(words) def clean_text( text ): # Function to convert a doc...
text = BeautifulSoup(review,'html.parser').get_text() # # 2. Remove non-letters text = re.sub("[^A-za-z0-9^,?!.\/'+-=]"," ", text) text = re.sub(r"what's", "what is ", text) text = re.sub(r"\'s", " ", text) text = re.sub(r"\'ve", " have ", text) text = re.sub(r"can't", "cannot ", text) t...
identifier_body
doExtractProj.py
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy at gmail dot com ************...
self.restoreGui() def restoreGui( self ): self.progressBar.setRange( 0, 100 ) self.progressBar.setValue( 0 ) QApplication.restoreOverrideCursor() QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.stopProcessing ) QObject.connect( self.buttonBox, SIGNAL( "rejected()" ), self...
self.extractor.stop() self.extractor = None
conditional_block
doExtractProj.py
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy at gmail dot com ************...
# ---------------------------------------------------------------------- def extractProjection( filename, createPrj ): raster = gdal.Open( unicode( filename ) ) crs = raster.GetProjection() geotransform = raster.GetGeoTransform() raster = None outFileName = os.path.splitext( unicode( filename ) )[0] # ...
random_line_split
doExtractProj.py
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy at gmail dot com ************...
( QThread ): def __init__( self, files, needPrj ): QThread.__init__( self, QThread.currentThread() ) self.inFiles = files self.needPrj = needPrj self.mutex = QMutex() self.stopMe = 0 def run( self ): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False ...
ExtractThread
identifier_name
doExtractProj.py
# -*- coding: utf-8 -*- """ *************************************************************************** doExtractProj.py --------------------- Date : August 2011 Copyright : (C) 2011 by Alexander Bruy Email : alexander dot bruy at gmail dot com ************...
self.emit( SIGNAL( "processIterrupted()" ) ) def stop( self ): self.mutex.lock() self.stopMe = 1 self.mutex.unlock() QThread.wait( self )
self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False for f in self.inFiles: extractProjection( f, self.needPrj ) self.emit( SIGNAL( "fileProcessed()" ) ) self.mutex.lock() s = self.stopMe self.mutex.unlock() if s == 1: interrupted = Tru...
identifier_body
jquery.countdown.js
/** * @name jQuery Countdown Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2011/12/countdown-jquery/ * @license MIT License */ (function($){ // Number of seconds in every time division var days = 24*60*60, hours = 60*60, minutes = 60; // Creating the plugin $.fn....
(position,number){ var digit = position.find('.digit') if(digit.is(':animated')){ return false; } if(position.data('digit') == number){ // We are already showing this number return false; } position.data('digit', number); var replacement = $('<span>',{ 'class':'digit', css:{ ...
switchDigit
identifier_name
jquery.countdown.js
/** * @name jQuery Countdown Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2011/12/countdown-jquery/ * @license MIT License */ (function($){ // Number of seconds in every time division var days = 24*60*60, hours = 60*60, minutes = 60; // Creating the plugin $.fn....
// Number of days left d = Math.floor(left / days); //Determine if we have more than 99 hours in the countdown; manydays = (d>99); if (manydays) { switchDigit(positions.eq(0),Math.floor(d/100)%100); updateDuo(1, 2, d); } else { updateDuo(0, 1, d); } left -= d*days...
{ left = 0; }
conditional_block
jquery.countdown.js
/** * @name jQuery Countdown Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2011/12/countdown-jquery/ * @license MIT License */ (function($){ // Number of seconds in every time division var days = 24*60*60, hours = 60*60, minutes = 60; // Creating the plugin $.fn....
return this; }; function init(elem, options){ elem.addClass('countdownHolder'); // Time left left = Math.floor((options.timestamp - (new Date())) / 1000); if(left < 0) { left = 0; } // Number of days left d = Math.floor(left / days); //Determine if we have mo...
{ switchDigit(positions.eq(minor),Math.floor(value/10)%10); switchDigit(positions.eq(major),value%10); }
identifier_body
jquery.countdown.js
/** * @name jQuery Countdown Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2011/12/countdown-jquery/ * @license MIT License */ (function($){ // Number of seconds in every time division var days = 24*60*60, hours = 60*60, minutes = 60; // Creating the plugin $.fn....
init(this, options); positions = this.find('.position'); (function tick(){ // Time left left = Math.floor((options.timestamp - (new Date())) / 1000); if(left < 0) { left = 0; } // Number of days left d = Math.floor(left / days); //Determine if we have more than 99 hou...
var left, d, h, m, s, positions; var manydays = false; // Initialize the plugin
random_line_split
mod.rs
pub fn solve(input: &String) -> String { let input = input.lines().nth(0).unwrap().to_string(); format!( "Skip 1: {} Skip n/2: {}", _solve(&input, &1), _solve(&input, &(input.len() / 2)) ) } fn _solve(input: &String, skip: &usize) -> usize { let nums: Vec<usize> = input.chars()...
() { assert_eq!(day1::_solve(&"1111".to_string(), &1), 4); } #[test] fn test_p1_3() { assert_eq!(day1::_solve(&"1234".to_string(), &1), 0); } #[test] fn test_p1_4() { assert_eq!(day1::_solve(&"91212129".to_string(), &1), 9); } #[test] fn test_p2_1() { ...
test_p1_2
identifier_name
mod.rs
pub fn solve(input: &String) -> String { let input = input.lines().nth(0).unwrap().to_string(); format!( "Skip 1: {} Skip n/2: {}", _solve(&input, &1), _solve(&input, &(input.len() / 2)) ) } fn _solve(input: &String, skip: &usize) -> usize { let nums: Vec<usize> = input.chars()...
#[test] fn test_p1_2() { assert_eq!(day1::_solve(&"1111".to_string(), &1), 4); } #[test] fn test_p1_3() { assert_eq!(day1::_solve(&"1234".to_string(), &1), 0); } #[test] fn test_p1_4() { assert_eq!(day1::_solve(&"91212129".to_string(), &1), 9); } #[test...
}
random_line_split
mod.rs
pub fn solve(input: &String) -> String { let input = input.lines().nth(0).unwrap().to_string(); format!( "Skip 1: {} Skip n/2: {}", _solve(&input, &1), _solve(&input, &(input.len() / 2)) ) } fn _solve(input: &String, skip: &usize) -> usize { let nums: Vec<usize> = input.chars()...
} sum } #[cfg(test)] mod test { use day1; #[test] fn test_p1_1() { assert_eq!(day1::_solve(&"1122".to_string(), &1), 3); } #[test] fn test_p1_2() { assert_eq!(day1::_solve(&"1111".to_string(), &1), 4); } #[test] fn test_p1_3() { assert_eq!(day1::...
{ sum += nums[i]; }
conditional_block
mod.rs
pub fn solve(input: &String) -> String { let input = input.lines().nth(0).unwrap().to_string(); format!( "Skip 1: {} Skip n/2: {}", _solve(&input, &1), _solve(&input, &(input.len() / 2)) ) } fn _solve(input: &String, skip: &usize) -> usize { let nums: Vec<usize> = input.chars()...
#[test] fn test_p2_1() { assert_eq!(day1::_solve(&"1212".to_string(), &2), 6); } #[test] fn test_p2_2() { assert_eq!(day1::_solve(&"1221".to_string(), &2), 0); } #[test] fn test_p2_3() { assert_eq!(day1::_solve(&"123425".to_string(), &3), 4); } #[test...
{ assert_eq!(day1::_solve(&"91212129".to_string(), &1), 9); }
identifier_body
socket.rs
/* Rust doesn't have unix datagram socket support at the moment. Hope I can ditch * this in the future. * Thanks to @gcourier for his rust-syslog library which I used as a reference. */ use libc; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::mem; use std::os::unix::io::RawFd; fn construct...
}
{ let (dst, len) = try!(construct_sockaddr(path)); let dstp = &dst as *const libc::sockaddr_storage; let ret = unsafe { libc::sendto(self.fd, buf.as_ptr() as *const libc::c_void, buf.len() as libc::size_t, ...
identifier_body
socket.rs
/* Rust doesn't have unix datagram socket support at the moment. Hope I can ditch * this in the future. * Thanks to @gcourier for his rust-syslog library which I used as a reference. */ use libc; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::mem; use std::os::unix::io::RawFd; fn construct...
s.sun_family = libc::AF_UNIX as libc::sa_family_t; for (slot, value) in s.sun_path.iter_mut().zip(path.as_bytes().iter()) { *slot = *value as i8; } let len = mem::size_of::<libc::sa_family_t>() + len + 1; return Ok((storage, len)); } fn unix_socket(ty: libc::c_int) -> Result<RawFd> { ...
{ let err = Error::new(ErrorKind::InvalidInput, "Socket path can not be longer than sizeof(sockaddr_storage) - 1"); return Err(err); }
conditional_block
socket.rs
/* Rust doesn't have unix datagram socket support at the moment. Hope I can ditch * this in the future. * Thanks to @gcourier for his rust-syslog library which I used as a reference. */ use libc; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::mem; use std::os::unix::io::RawFd; fn construct...
return Err(err); } s.sun_family = libc::AF_UNIX as libc::sa_family_t; for (slot, value) in s.sun_path.iter_mut().zip(path.as_bytes().iter()) { *slot = *value as i8; } let len = mem::size_of::<libc::sa_family_t>() + len + 1; return Ok((storage, len)); } fn unix_socket(ty: lib...
if len > s.sun_path.len() - 1 { let err = Error::new(ErrorKind::InvalidInput, "Socket path can not be longer than sizeof(sockaddr_storage) - 1");
random_line_split
socket.rs
/* Rust doesn't have unix datagram socket support at the moment. Hope I can ditch * this in the future. * Thanks to @gcourier for his rust-syslog library which I used as a reference. */ use libc; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::mem; use std::os::unix::io::RawFd; fn
(path: &CString) -> Result<(libc::sockaddr_storage, usize)> { assert!(mem::size_of::<libc::sockaddr_storage>() >= mem::size_of::<libc::sockaddr_un>()); let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let s: &mut libc::sockaddr_un = unsafe { mem::transmute(&mut storage) }; ...
construct_sockaddr
identifier_name
mod.rs
// Copyright 2017 CoreOS, 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...
let key: String = self .client .get( retry::Raw, AwsProvider::endpoint_for( &format!("meta-data/public-keys/{}/openssh-key", tokens[0]), false, ...
{ return Err("error parsing keyID".into()); }
conditional_block
mod.rs
// Copyright 2017 CoreOS, 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...
#[derive(Clone, Debug)] pub struct AwsProvider { client: retry::Client, } impl AwsProvider { pub fn try_new() -> Result<AwsProvider> { let client = retry::Client::try_new()?.return_on_404(true); AwsProvider::with_client(client) } fn with_client(client: retry::Client) -> Result<AwsProv...
random_line_split
mod.rs
// Copyright 2017 CoreOS, 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...
(key: &str, _use_latest: bool) -> String { let url = mockito::server_url(); format!("{}/{}", url, key) } #[cfg(not(test))] fn endpoint_for(key: &str, use_latest: bool) -> String { const URL: &str = "http://169.254.169.254/2019-10-01"; const URL_LATEST: &str = "http://169.254...
endpoint_for
identifier_name
mod.rs
// Copyright 2017 CoreOS, 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...
#[cfg(not(test))] fn endpoint_for(key: &str, use_latest: bool) -> String { const URL: &str = "http://169.254.169.254/2019-10-01"; const URL_LATEST: &str = "http://169.254.169.254/latest"; if use_latest { format!("{}/{}", URL_LATEST, key) } else { format!...
{ let url = mockito::server_url(); format!("{}/{}", url, key) }
identifier_body
template.py
# -*- coding: utf-8 -*- # pylint: disable-msg=W0104,E0602,W0613,R0201 """ Abstract classes and utilities for template engines """ from hyde._compat import with_metaclass from hyde.exceptions import HydeException import abc from commando.util import getLoggerWithNullHandler, load_python_object DEFAULT_TEMPLATE = 'hyd...
(self, sitepath): self.sitepath = sitepath self.logger = getLoggerWithNullHandler(self.__class__.__name__) @abc.abstractmethod def configure(self, site, engine): """ The site object should contain a config attribute. The config object is a simple YAML object with require...
__init__
identifier_name
template.py
# -*- coding: utf-8 -*- # pylint: disable-msg=W0104,E0602,W0613,R0201 """ Abstract classes and utilities for template engines """ from hyde._compat import with_metaclass from hyde.exceptions import HydeException import abc from commando.util import getLoggerWithNullHandler, load_python_object DEFAULT_TEMPLATE = 'hyd...
return self.q(selector).html() class Template(with_metaclass(abc.ABCMeta)): """ Interface for hyde template engines. To use a different template engine, the following interface must be implemented. """ def __init__(self, sitepath): self.sitepath = sitepath self.logger = ...
return self.raw
conditional_block
template.py
# -*- coding: utf-8 -*- # pylint: disable-msg=W0104,E0602,W0613,R0201 """ Abstract classes and utilities for template engines """ from hyde._compat import with_metaclass from hyde.exceptions import HydeException import abc from commando.util import getLoggerWithNullHandler, load_python_object DEFAULT_TEMPLATE = 'hyd...
""" Reads the configuration to find the appropriate template. """ template_object = site.config.get('template', DEFAULT_TEMPLATE) template_cls = load_python_object(template_object) template = template_cls(site.sitepath) return template
identifier_body
template.py
# -*- coding: utf-8 -*- # pylint: disable-msg=W0104,E0602,W0613,R0201 """ Abstract classes and utilities for template engines """ from hyde._compat import with_metaclass from hyde.exceptions import HydeException import abc from commando.util import getLoggerWithNullHandler, load_python_object DEFAULT_TEMPLATE = 'hyd...
""" Patterns for matching selected template statements. """ return {} @abc.abstractmethod def get_include_statement(self, path_to_include): """ Returns an include statement for the current template, given the path to include. """ return '{...
def exception_class(self): return HydeException @abc.abstractproperty def patterns(self):
random_line_split
video.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'video-showcase', template: ` <div class="video-showcase"> <h1>Welcome to our Songs App</h1> <video width="400" controls> <source src="https://redirector.googlevideo.com/videoplayback?itag=22&ei=Vbe2WeL7MoWvVO3FhcAK&sparams=dur%2Cei%2Cid%2Cinitc...
} `] }) export class VideoComponent { }
flex-flow: column; align-items: center; justify-content: center; padding-top: 20px;
random_line_split
video.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'video-showcase', template: ` <div class="video-showcase"> <h1>Welcome to our Songs App</h1> <video width="400" controls> <source src="https://redirector.googlevideo.com/videoplayback?itag=22&ei=Vbe2WeL7MoWvVO3FhcAK&sparams=dur%2Cei%2Cid%2Cinitc...
{ }
VideoComponent
identifier_name
ng_form_model.d.ts
import { SimpleChange, OnChanges } from 'angular2/core'; import { NgControl } from './ng_control'; import { NgControlGroup } from './ng_control_group'; import { ControlContainer } from './control_container'; import { Form } from './form_interface'; import { Control, ControlGroup } from '../model'; /** * Binds an exist...
extends ControlContainer implements Form, OnChanges { private _validators; private _asyncValidators; form: ControlGroup; directives: NgControl[]; ngSubmit: any; constructor(_validators: any[], _asyncValidators: any[]); ngOnChanges(changes: { [key: string]: SimpleChange; }): void...
NgFormModel
identifier_name
ng_form_model.d.ts
import { SimpleChange, OnChanges } from 'angular2/core'; import { NgControl } from './ng_control'; import { NgControlGroup } from './ng_control_group'; import { ControlContainer } from './control_container'; import { Form } from './form_interface'; import { Control, ControlGroup } from '../model'; /** * Binds an exist...
* directives: [FORM_DIRECTIVES] * }) * export class App { * loginForm: ControlGroup; * * constructor() { * this.loginForm = new ControlGroup({ * login: new Control(""), * password: new Control("") * }); * } * * get value(): string { * return JSON.stringify(this.loginForm....
* `,
random_line_split
users_widget.tsx
/* * Copyright 2022 ThoughtWorks, 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 agr...
interface UsersWidgetAttrs { roleAttributes: Stream<GoCDAttributes>; selectedUser?: string; readOnly?: boolean; } export class UsersWidget extends MithrilViewComponent<UsersWidgetAttrs> { view(vnode: m.Vnode<UsersWidgetAttrs>): m.Children | void | null { return vnode.attrs.roleAttributes().users.map((user)...
import Stream from "mithril/stream"; import {GoCDAttributes} from "models/roles/roles"; import styles from "./index.scss";
random_line_split
users_widget.tsx
/* * Copyright 2022 ThoughtWorks, 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 agr...
} private static readOnlyView(vnode: m.Vnode<UsersWidgetAttrs>) { return !(false === vnode.attrs.readOnly); } }
{ attributes().deleteUser(username); }
identifier_body
users_widget.tsx
/* * Copyright 2022 ThoughtWorks, 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 agr...
(username) { attributes().deleteUser(username); } } private static readOnlyView(vnode: m.Vnode<UsersWidgetAttrs>) { return !(false === vnode.attrs.readOnly); } }
if
identifier_name
users_widget.tsx
/* * Copyright 2022 ThoughtWorks, 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 agr...
} private static readOnlyView(vnode: m.Vnode<UsersWidgetAttrs>) { return !(false === vnode.attrs.readOnly); } }
{ mayBeDeleteButton = ( <span aria-hidden="true" class={styles.roleUserDeleteIcon} onclick={UsersWidget.deleteUserFromRole.bind(this, vnode.attrs.roleAttributes, us...
conditional_block
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::marker::PhantomData; use std::sync::Arc; use async_trait::async_trait; use edenapi::BlockingResponse; use edenapi::EdenApi; use e...
use types::Key; use crate::datastore::HgIdMutableDeltaStore; use crate::datastore::RemoteDataStore; use crate::historystore::HgIdMutableHistoryStore; use crate::historystore::RemoteHistoryStore; use crate::remotestore::HgIdRemoteStore; use crate::types::StoreKey; mod data; mod history; use data::EdenApiDataStore; us...
use edenapi_types::FileResponse; use edenapi_types::FileSpec; use edenapi_types::TreeAttributes; use edenapi_types::TreeEntry;
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::marker::PhantomData; use std::sync::Arc; use async_trait::async_trait; use edenapi::BlockingResponse; use edenapi::EdenApi; use e...
fn historystore( self: Arc<Self>, _store: Arc<dyn HgIdMutableHistoryStore>, ) -> Arc<dyn RemoteHistoryStore> { unimplemented!("EdenAPI does not support fetching tree history") } } /// Marker type indicating that the store fetches file data. pub enum File {} /// Marker type indica...
{ Arc::new(EdenApiDataStore::new(self, store)) }
identifier_body
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::marker::PhantomData; use std::sync::Arc; use async_trait::async_trait; use edenapi::BlockingResponse; use edenapi::EdenApi; use e...
(client: Arc<dyn EdenApi>) -> Arc<Self> { Arc::new(Self { client, _phantom: PhantomData, }) } } impl HgIdRemoteStore for EdenApiRemoteStore<File> { fn datastore( self: Arc<Self>, store: Arc<dyn HgIdMutableDeltaStore>, ) -> Arc<dyn RemoteDataStore> { ...
new
identifier_name
product-info.controller.js
angular.module('elementBoxApp.products.productInfo') .controller('ProductInfoCtrl', [ '$scope', '$rootScope', '$state', '$stateParams', '$timeout', 'ModalAlert', 'ProductsService', 'UserService', 'CommentsService', 'EVENT_NAMES', function($scope, $rootScope, $state, $stateParams, $timeout, Modal...
if (!$scope.currentUser || !$scope.currentUser.id) { onNeedToLogin(); return; } var newComment = { prodId: $stateParams.productId, text: commentTxt }; CommentsService.save(newComment, function(data) { $scope.fetchPage(); $rootScope.$emit(E...
{ return; }
conditional_block
product-info.controller.js
angular.module('elementBoxApp.products.productInfo') .controller('ProductInfoCtrl', [ '$scope', '$rootScope', '$state', '$stateParams', '$timeout', 'ModalAlert', 'ProductsService', 'UserService', 'CommentsService', 'EVENT_NAMES', function($scope, $rootScope, $state, $stateParams, $timeout, ModalA...
return onNeedToLogin(); } UserService.addToWishList({ prodId: $scope.product._id }, function() { $rootScope.$emit(EVENT_NAMES.addWishList, $scope.product); }); }; $scope.removeFromWishList = function() { UserService.removeFromWishList({ itemId: $scope.product._id }, fun...
$scope.addToWishList = function() { if (!$scope.currentUser || !$scope.currentUser.id) {
random_line_split
process_data.py
import cPickle import numpy as np import sys from collections import OrderedDict def format_chars(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i...
def digits(n): digit_str = '' for i in range(n): digit_str = digit_str + 'DIGIT' return digit_str def establishdic(fname, gname, hname, binfile): data = open(fname, "rb").readlines() + open(gname, "rb").readlines() + open(hname, "rb").readlines() char_dict = OrderedDict() vocab_dict ...
if len(s)>4 and s[:5] == "http:": return True else: return False
identifier_body
process_data.py
import cPickle import numpy as np import sys from collections import OrderedDict def format_chars(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i...
# generate char dictionary chars = list(vocab) for char in chars: if char not in char_dict: char_dict[char] = char_count char_count += 1 pos_dictionary = OrderedDict() pos_dictionary['words2idx'] = vocab_dict pos_dictionary['labels2idx...
tag_dict[tag] = tag_count tag_count += 1
conditional_block
process_data.py
import cPickle import numpy as np import sys from collections import OrderedDict def
(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i] = [0] * (to_pad / 2) + chars_sent_ls[i] + [0] * (to_pad / 2) else: chars_sen...
format_chars
identifier_name
process_data.py
import cPickle import numpy as np import sys from collections import OrderedDict def format_chars(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i...
outfilename = sys.argv[5] pos_dictionary = establishdic(fname, gname, hname, binfile) train_pos, valid_pos, test_pos = sepdata(fname, gname, hname, pos_dictionary) print "train pos examples", len(train_pos[0]) print "valid pos examples", len(valid_pos[0]) print "test pos examples", len(test_p...
random_line_split
OnSelect.tsx
import React, { ReactText, useState } from 'react'; import { Box, DataTable, Meter, Text } from 'grommet'; import { ColumnConfig } from '../..'; // This story uses TypeScript const amountFormatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, }); // Type anno...
<Box align="center" pad="large"> <DataTable columns={columns} data={DATA} step={10} select={select} onSelect={setSelect} /> </Box> // </Grommet> ); }; OnSelectDataTable.storyName = 'OnSelect'; export default { title: 'Visualizations/DataTable/OnSelec...
return ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={grommet}>
random_line_split
coherence-overlap-issue-23516-inherent.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) { } } fn main() { }
dummy
identifier_name
coherence-overlap-issue-23516-inherent.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 ...
struct Cake<X>(X); impl<T:Sugar> Cake<T> { fn dummy(&self) { } } //~^ ERROR E0592 impl<U:Sugar> Cake<Box<U>> { fn dummy(&self) { } } fn main() { }
// though we see no impl of `Sugar` for `Box`. Therefore, an overlap // error is reported for the following pair of impls (#23516). pub trait Sugar {}
random_line_split
DropDownField.tsx
/*
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import { Box } from './Box'; import { Field } from './Field'; export interface DropDownItem { id: string; value: string; } const ListBoxContainer = styled.div` po...
* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this
random_line_split
DropDownField.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import { Box } from './Bo...
(props: DropDownProps<TValue>) { super(props); this.state = { open: false }; } public render() { const { open } = this.state; const { selected, items } = this.props; return ( <ListBoxContainer> <ListBox onClick={this.toggleOpen}> {this.props.renderItem ? this.props.render...
constructor
identifier_name
DropDownField.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { styled } from '@csegames/linaria/react'; import { Box } from './Bo...
public render() { const { open } = this.state; const { selected, items } = this.props; return ( <ListBoxContainer> <ListBox onClick={this.toggleOpen}> {this.props.renderItem ? this.props.renderItem(selected) : selected + ''} <i className={`fa ${ open ? 'fa-caret-down' : ...
{ super(props); this.state = { open: false }; }
identifier_body
read_pool.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. //! Distinct thread pools to handle read commands having different priority levels. use crate::config::StorageReadPoolConfig; use crate::storage::kv::{destroy_tls_engine, set_tls_engine, Engine, FlowStatsReporter}; use crate::storage::metrics; use fil...
destroy_tls_engine::<E>(); }) .build_future_pool() }) .collect() } /// Build a thread pool that has default tick behavior for testing. pub fn build_read_pool_for_test<E: Engine>( config: &StorageReadPoolConfig, engine: E, ) -> Vec<FuturePool>...
{ let names = vec!["store-read-low", "store-read-normal", "store-read-high"]; let configs: Vec<Config> = config.to_yatp_pool_configs(); assert_eq!(configs.len(), 3); configs .into_iter() .zip(names) .map(|(config, name)| { let reporter = reporter.clone(); ...
identifier_body
read_pool.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. //! Distinct thread pools to handle read commands having different priority levels. use crate::config::StorageReadPoolConfig; use crate::storage::kv::{destroy_tls_engine, set_tls_engine, Engine, FlowStatsReporter}; use crate::storage::metrics; use fil...
configs .into_iter() .zip(names) .map(|(config, name)| { let reporter = reporter.clone(); let engine = Arc::new(Mutex::new(engine.clone())); YatpPoolBuilder::new(FuturePoolTicker { reporter }) .name_prefix(name) .config(con...
engine: E, ) -> Vec<FuturePool> { let names = vec!["store-read-low", "store-read-normal", "store-read-high"]; let configs: Vec<Config> = config.to_yatp_pool_configs(); assert_eq!(configs.len(), 3);
random_line_split
read_pool.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. //! Distinct thread pools to handle read commands having different priority levels. use crate::config::StorageReadPoolConfig; use crate::storage::kv::{destroy_tls_engine, set_tls_engine, Engine, FlowStatsReporter}; use crate::storage::metrics; use fil...
<E: Engine, R: FlowStatsReporter>( config: &StorageReadPoolConfig, reporter: R, engine: E, ) -> Vec<FuturePool> { let names = vec!["store-read-low", "store-read-normal", "store-read-high"]; let configs: Vec<Config> = config.to_yatp_pool_configs(); assert_eq!(configs.len(), 3); configs ...
build_read_pool
identifier_name
datastore.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
else: storage_class = _YAMLStorage self.db = tinydb.TinyDB(str(path), storage=storage_class) logger.debug(f"Datastore init: {self.path} read_only={read_only}") # Force the datastore to be read by making a query, otherwise it is # only read on the first access. ...
storage_class = _YAMLStorageReadOnly
conditional_block
datastore.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
) return db_data def write(self, data) -> None: """Write database (data) to file.""" logger.debug(f"_YAMLStorage write: {self.path} data={data!r}") self.path.write_text(yaml.dump(data)) def close(self): """Nothing to do since we do not keep <path> open.""" ...
"""Provide YAML-backed storage for TinyDB.""" def __init__(self, path: str): self.path = pathlib.Path(path) logger.debug(f"_YAMLStorage init {self.path}") def read(self) -> Dict[str, Any]: """Read database from file.""" logger.debug(f"_YAMLStorage read: {self.path}") tr...
identifier_body
datastore.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
self.db = tinydb.TinyDB(str(path), storage=storage_class) logger.debug(f"Datastore init: {self.path} read_only={read_only}") # Force the datastore to be read by making a query, otherwise it is # only read on the first access. _ = self.db.tables() # Nothing left to do i...
random_line_split
datastore.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
(self, data) -> None: """Ignore any writes in read-only mode.""" class Datastore: """Datastore class, providing context manager for TinyDB. Manages migrations and storage requirements. If migrations do not indicate support for current datastore version, SnapcraftDatastoreVersionUnsupported w...
write
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate malloc_size_of_derive; use app_units::{Au, MAX_AU, MIN_AU}; use euclid::{ default:...
() -> Rect<Au> { Rect::new( Point2D::new(MIN_AU / 2, MIN_AU / 2), Size2D::new(MAX_AU, MAX_AU), ) } } impl MaxRect for LayoutRect { fn max_rect() -> LayoutRect { LayoutRect::new( LayoutPoint::new(f32::MIN / 2.0, f32::MIN / 2.0), LayoutSize:...
max_rect
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate malloc_size_of_derive; use app_units::{Au, MAX_AU, MIN_AU}; use euclid::{ default:...
LayoutSize::new(f32::MAX, f32::MAX), ) } } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new( Point2D::new( Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect....
LayoutRect::new( LayoutPoint::new(f32::MIN / 2.0, f32::MIN / 2.0),
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate malloc_size_of_derive; use app_units::{Au, MAX_AU, MIN_AU}; use euclid::{ default:...
} impl MaxRect for LayoutRect { fn max_rect() -> LayoutRect { LayoutRect::new( LayoutPoint::new(f32::MIN / 2.0, f32::MIN / 2.0), LayoutSize::new(f32::MAX, f32::MAX), ) } } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_t...
{ Rect::new( Point2D::new(MIN_AU / 2, MIN_AU / 2), Size2D::new(MAX_AU, MAX_AU), ) }
identifier_body
server-edit.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router' import { Observable } from 'rxjs/Observable'; import { Server } from '../../shared/server.model' import { ServersService } from '../servers.service'; import { CanDeactivateGuard } ...
else if (!this.changesSaved) { // confirm() method is a nifty way to receive a boolean from the user return confirm('Do you want to discard the changes?'); } else { return true; } } }
{ return true; }
conditional_block
server-edit.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router' import { Observable } from 'rxjs/Observable'; import { Server } from '../../shared/server.model' import { ServersService } from '../servers.service'; import { CanDeactivateGuard } ...
() { const name = this.name.nativeElement.value; const status = this.status.nativeElement.value; this.server = new Server(this.server.id, name, status); this.serversService.updateServer(this.server); this.changesSaved = true; this.router.navigate(["/servers", this.server.id]); } // this met...
onServerUpdate
identifier_name
server-edit.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router' import { Observable } from 'rxjs/Observable'; import { Server } from '../../shared/server.model' import { ServersService } from '../servers.service'; import { CanDeactivateGuard } ...
} ); this.activatedRoute.queryParams.subscribe( (queryParams: Params) => { this.allowEdit = queryParams['allowEdit'] === '1' ? true : false; } ); } onServerUpdate() { const name = this.name.nativeElement.value; const status = this.status.nativeElement.value; this.s...
this.activatedRoute.params.subscribe( (params: Params) => { this.server = this.serversService.getServerByID(params.id); this.serverStatusOptions = this.serversService.getServerStatusOptions();
random_line_split
DialogManager.tsx
// ==LICENSE-BEGIN== // Copyright 2017 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the proj...
public render(): React.ReactElement<{}> { const dialog = this.props.dialog; if (!dialog || !dialog.open) { return (<></>); } return ( <> <PublicationInfo></PublicationInfo> </> ); } } const mapStateToProps = (state...
{ super(props); }
identifier_body
DialogManager.tsx
// ==LICENSE-BEGIN== // Copyright 2017 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the proj...
(props: IProps) { super(props); } public render(): React.ReactElement<{}> { const dialog = this.props.dialog; if (!dialog || !dialog.open) { return (<></>); } return ( <> <PublicationInfo></PublicationInfo> </> ...
constructor
identifier_name
DialogManager.tsx
// ==LICENSE-BEGIN== // Copyright 2017 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the proj...
return ( <> <PublicationInfo></PublicationInfo> </> ); } } const mapStateToProps = (state: IReaderRootState, _props: IBaseProps) => { return { dialog: state.dialog, }; }; export default connect(mapStateToProps)(DialogManager);
{ return (<></>); }
conditional_block
DialogManager.tsx
// ==LICENSE-BEGIN== // Copyright 2017 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the proj...
}; }; export default connect(mapStateToProps)(DialogManager);
random_line_split
inotify.rs
//! Monitoring API for filesystem events. //! //! Inotify is a Linux-only API to monitor filesystems events. //! //! For more documentation, please read [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). //! //! # Examples //! //! Monitor all events happening in directory "test": //! ```no_run //! # us...
}
{ Inotify { fd } }
identifier_body
inotify.rs
//! Monitoring API for filesystem events. //! //! Inotify is a Linux-only API to monitor filesystems events. //! //! For more documentation, please read [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). //! //! # Examples //! //! Monitor all events happening in directory "test": //! ```no_run //! # us...
}; events.push(InotifyEvent { wd: WatchDescriptor { wd: event.wd }, mask: AddWatchFlags::from_bits_truncate(event.mask), cookie: event.cookie, name }); offset += header_size + event.len as usize; }...
{ let ptr = unsafe { buffer .as_ptr() .add(offset + header_size) as *const c_char }; let cstr = unsafe { CStr::from_ptr(ptr) }; Som...
conditional_block
inotify.rs
//! Monitoring API for filesystem events. //! //! Inotify is a Linux-only API to monitor filesystems events. //! //! For more documentation, please read [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). //! //! # Examples //! //! Monitor all events happening in directory "test": //! ```no_run //! # us...
{ /// Watch descriptor. This field corresponds to the watch descriptor you /// were issued when calling add_watch. It allows you to know which watch /// this event comes from. pub wd: WatchDescriptor, /// Event mask. This field is a bitfield describing the exact event that /// occured. pub ...
InotifyEvent
identifier_name
inotify.rs
//! Monitoring API for filesystem events. //! //! Inotify is a Linux-only API to monitor filesystems events. //! //! For more documentation, please read [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). //! //! # Examples //! //! Monitor all events happening in directory "test": //! ```no_run //! # us...
pub mask: AddWatchFlags, /// This cookie is a number that allows you to connect related events. For /// now only IN_MOVED_FROM and IN_MOVED_TO can be connected. pub cookie: u32, /// Filename. This field exists only if the event was triggered for a file /// inside the watched directory. pub n...
/// were issued when calling add_watch. It allows you to know which watch /// this event comes from. pub wd: WatchDescriptor, /// Event mask. This field is a bitfield describing the exact event that /// occured.
random_line_split
test_1A_notebook_soft_sql.py
# -*- coding: utf-8 -*- """ @brief test log(time=92s) """ import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, add_missing_development_version import ensae_teaching_cs class TestNotebookRunner1a_soft_sql(unittest.TestCase): def setUp(self): add_m...
if __name__ == "__main__": unittest.main()
fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") temp = get_temp_folder(__file__, "temp_notebook1a_soft_sql") from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a keepnote = l...
identifier_body
test_1A_notebook_soft_sql.py
# -*- coding: utf-8 -*- """ @brief test log(time=92s) """ import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, add_missing_development_version import ensae_teaching_cs class TestNotebookRunner1a_soft_sql(unittest.TestCase): def setUp(self): add_m...
temp = get_temp_folder(__file__, "temp_notebook1a_soft_sql") from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a keepnote = ls_notebooks("td1a_soft") for n in keepnote: fLOG(n) execute_notebooks(temp, keepno...
OutputPrint=__name__ == "__main__")
random_line_split
test_1A_notebook_soft_sql.py
# -*- coding: utf-8 -*- """ @brief test log(time=92s) """ import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, add_missing_development_version import ensae_teaching_cs class TestNotebookRunner1a_soft_sql(unittest.TestCase): def setUp(self): add_m...
unittest.main()
conditional_block
test_1A_notebook_soft_sql.py
# -*- coding: utf-8 -*- """ @brief test log(time=92s) """ import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, add_missing_development_version import ensae_teaching_cs class TestNotebookRunner1a_soft_sql(unittest.TestCase): def setUp(self): add_m...
(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") temp = get_temp_folder(__file__, "temp_notebook1a_soft_sql") from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a ...
test_notebook_runner_soft_sql
identifier_name
foreign-link-switcher.ts
export class ForeignLinkSwitcher { private static instance: ForeignLinkSwitcher; private static initPage = location.href; foreignLinkCheckbox = document.getElementById('has_foreign_link') as HTMLInputElement; foreignLinkSwitchedEl = document.getElementById('event_foreign_link_box') as HTMLDivElement; fore...
} bindEvents() { this.foreignLinkCheckbox.addEventListener('change', (_: Event) => { this.foreignLinkSwitchedEl.classList.toggle('hidden'); if (!this.isChecked) { this.foreignLinkInput.value = ''; this.foreignLinkInput.setAttribute('disable', 'disabled'); } else { this...
random_line_split
foreign-link-switcher.ts
export class ForeignLinkSwitcher { private static instance: ForeignLinkSwitcher; private static initPage = location.href; foreignLinkCheckbox = document.getElementById('has_foreign_link') as HTMLInputElement; foreignLinkSwitchedEl = document.getElementById('event_foreign_link_box') as HTMLDivElement; fore...
bindEvents() { this.foreignLinkCheckbox.addEventListener('change', (_: Event) => { this.foreignLinkSwitchedEl.classList.toggle('hidden'); if (!this.isChecked) { this.foreignLinkInput.value = ''; this.foreignLinkInput.setAttribute('disable', 'disabled'); } else { this.fo...
{ if (this.isChecked) this.foreignLinkSwitchedEl.classList.remove('hidden'); this.bindEvents(); }
identifier_body
foreign-link-switcher.ts
export class
{ private static instance: ForeignLinkSwitcher; private static initPage = location.href; foreignLinkCheckbox = document.getElementById('has_foreign_link') as HTMLInputElement; foreignLinkSwitchedEl = document.getElementById('event_foreign_link_box') as HTMLDivElement; foreignLinkInput = document.getEleme...
ForeignLinkSwitcher
identifier_name
error.rs
2 — Syntax Error or Access Rule Violation "42000" => SyntaxErrorOrAccessRuleViolation, "42601" => SyntaxError, "42501" => InsufficientPrivilege, "42846" => CannotCoerce, "42803" => GroupingError, "42P20" => WindowingError, "42P19" => InvalidRecursion, "42830" => InvalidForeignKey, "4...
message),
identifier_name
error.rs
, "22002" => NullValueNoIndicatorParameter, "22003" => NumericValueOutOfRange, "22026" => StringDataLengthMismatch, "22001" => StringDataRightTruncationException, "22011" => SubstringError, "22027" => TrimError, "22024" => UnterminatedCString, "2200F" => ZeroLengthCharacterString, "2...
"2F003" => ProhibitedSqlStatementAttemptedSqlRoutine, "2F004" => ReadingSqlDataNotPermittedSqlRoutine, // Class 34 — Invalid Cursor Name "34000" => InvalidCursorName, // Class 38 — External Routine Exception "38000" => ExternalRoutineException, "38001" => ContainingSqlNotPermitted, "38...
"2F002" => ModifyingSqlDataNotPermittedSqlRoutine,
random_line_split
error.rs
"HV00D" => FdwInvalidOptionName, "HV090" => FdwInvalidStringLengthOrBufferLength, "HV00A" => FdwInvalidStringFormat, "HV009" => FdwInvalidUseOfNullPointer, "HV014" => FdwTooManyHandles, "HV001" => FdwOutOfMemory, "HV00P" => FdwNoSchemas, "HV00J" => FdwOptionNameNotFound, "HV00K" => F...
ncountered when communicating with the Postgres server #[deriving(
identifier_body
parameters.js
/* * This file is part of the cb50_ctrl distribution (https://github.com/johnerlandsson/cb50_ctrl). * Copyright (c) 2017 John Erlandsson * * This program 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 Foundat...
(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; ...
clone
identifier_name
parameters.js
/* * This file is part of the cb50_ctrl distribution (https://github.com/johnerlandsson/cb50_ctrl). * Copyright (c) 2017 John Erlandsson * * This program 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 Foundat...
} // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } //The module angular.module("ParameterApp", ['ui-notifi...
{ var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; fo...
identifier_body
parameters.js
/* * This file is part of the cb50_ctrl distribution (https://github.com/johnerlandsson/cb50_ctrl). * Copyright (c) 2017 John Erlandsson * * This program 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 Foundat...
//The module angular.module("ParameterApp", ['ui-notification']).controller("ParameterCtrl", function($scope, $http, Notification) { $scope.parametersLoaded = false; $scope.runMsgVisible = false; $scope.spinnerVisible = true; $scope.parametersVisible = false; $scope.parameters = { regulator: { Kp:...
random_line_split
test_fabs28_detached_award_financial_assistance_1.py
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs28_detached_award_financial_assistance_1' def test_column_headers(database): expected_subset = {'row_number', 'assistance_type', ...
(database): """ FaceValueOfDirectLoanOrLoanGuarantee is required for loans (i.e., when AssistanceType = 07 or 08). """ det_award = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=0, correction_delete_indicatr='') ...
test_success
identifier_name
test_fabs28_detached_award_financial_assistance_1.py
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs28_detached_award_financial_assistance_1' def test_column_headers(database): expected_subset = {'row_number', 'assistance_type', ...
# Ignore correction delete indicator of D det_award_3 = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=None, correction_delete_indicatr='d') errors = number_of_errors(_FILE, database, models=[det_award, det_a...
random_line_split
test_fabs28_detached_award_financial_assistance_1.py
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs28_detached_award_financial_assistance_1' def test_column_headers(database): expected_subset = {'row_number', 'assistance_type', ...
def test_failure(database): """ FaceValueOfDirectLoanOrLoanGuarantee is required for loans (i.e., when AssistanceType = 07 or 08). """ det_award = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=None, correction_...
""" FaceValueOfDirectLoanOrLoanGuarantee is required for loans (i.e., when AssistanceType = 07 or 08). """ det_award = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=0, correction_delete_indicatr='') det_award_2 = ...
identifier_body
main.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![warn(clippy::all)] mod client; mod error_reporting; mod lsp; mod server; use lsp_server::Connection; use std::error::Error; us...
} }
{ // Test with an in-memory connection pair let (connection, client) = Connection::memory(); // Mock set of client parameters. The `root_path` field is deprecated, but // still required to construct the params, so we allow deprecated fields here. #[allow(deprecated)] let ...
identifier_body
main.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */
mod client; mod error_reporting; mod lsp; mod server; use lsp_server::Connection; use std::error::Error; use env_logger::Env; use log::info; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Sync + Send>> { env_logger::from_env(Env::default().default_filter_or("info, warn, error, debug")).init(); ...
#![warn(clippy::all)]
random_line_split
main.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![warn(clippy::all)] mod client; mod error_reporting; mod lsp; mod server; use lsp_server::Connection; use std::error::Error; us...
() -> Result<(), Box<dyn Error + Sync + Send>> { env_logger::from_env(Env::default().default_filter_or("info, warn, error, debug")).init(); let (connection, io_handles) = Connection::stdio(); info!("Initialized stdio transport layer"); let params = server::initialize(&connection)?; info!("JSON-RPC h...
main
identifier_name
q008.py
#------------------------------------------------------------------------------- # Name: Largest Product in a Series # Purpose: The four adjacent digits in the 1000-digit number (provided in # textfile 'q008.txt') that have the greatest product are # 9 x 9 x 8 x 9 = 5832. Find the...
numbers = readNums() currentSum = 0 DIGITS = 13 for i in range(len(numbers)): digitSum = 1 if i < (len(numbers) - DIGITS): for k in range(DIGITS): digitSum *= numbers[i+k] if digitSum > currentSum: currentSum = digitSum print currentSum
file = open("q008.txt") nums = [] for line in file: line = line.strip() for i in range (len(line)): nums += [int(line[i])] return nums
identifier_body
q008.py
#------------------------------------------------------------------------------- # Name: Largest Product in a Series # Purpose: The four adjacent digits in the 1000-digit number (provided in # textfile 'q008.txt') that have the greatest product are # 9 x 9 x 8 x 9 = 5832. Find the...
print currentSum
currentSum = digitSum
conditional_block
q008.py
#------------------------------------------------------------------------------- # Name: Largest Product in a Series # Purpose: The four adjacent digits in the 1000-digit number (provided in # textfile 'q008.txt') that have the greatest product are # 9 x 9 x 8 x 9 = 5832. Find the...
(): file = open("q008.txt") nums = [] for line in file: line = line.strip() for i in range (len(line)): nums += [int(line[i])] return nums numbers = readNums() currentSum = 0 DIGITS = 13 for i in range(len(numbers)): digitSum = 1 if i < (len(numbers) - DIGITS): ...
readNums
identifier_name
q008.py
#------------------------------------------------------------------------------- # Name: Largest Product in a Series # Purpose: The four adjacent digits in the 1000-digit number (provided in # textfile 'q008.txt') that have the greatest product are # 9 x 9 x 8 x 9 = 5832. Find the...
currentSum = digitSum print currentSum
if digitSum > currentSum:
random_line_split
cmd_connect.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class ConnectCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "ConnectCommand" core = True ...
user.sendMessage("NOTICE", "*** Failed to connect to {}; it's likely not configured.".format(serverName)) return True connectCmd = ConnectCommand()
user.sendMessage("NOTICE", "*** Connecting to {}".format(serverName)) else:
random_line_split
cmd_connect.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class ConnectCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "ConnectCommand" core = True ...
return True connectCmd = ConnectCommand()
user.sendMessage("NOTICE", "*** Failed to connect to {}; it's likely not configured.".format(serverName))
conditional_block
cmd_connect.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class
(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "ConnectCommand" core = True def actions(self): return [ ("commandpermission-CONNECT", 1, self.canConnect) ] def userCommands(self): return [ ("CONNECT", 1, self) ] def canConnect(self, user, data): if not self.ircd.runActionUn...
ConnectCommand
identifier_name
cmd_connect.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class ConnectCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "ConnectCommand" core = True ...
def execute(self, user, data): serverName = data["server"] if serverName in self.ircd.serverNames: user.sendMessage("NOTICE", "*** Server {} is already on the network".format(serverName)) elif self.ircd.connectServer(serverName): user.sendMessage("NOTICE", "*** Connecting to {}".format(serverName)) el...
if not params: user.sendSingleError("ConnectParams", irc.ERR_NEEDMOREPARAMS, "CONNECT", "Not enough parameters") return None return { "server": params[0] }
identifier_body
colormap.py
#!/usr/bin/env python
These functions, when given a magnitude mag between cmin and cmax, return a colour tuple (red, green, blue). Light blue is cold (low magnitude) and yellow is hot (high magnitude). """ import math def floatRgb(mag, cmin, cmax, alpha=1.0): """ Return a tuple of floats between 0 and 1 for the red, green an...
# """
random_line_split
colormap.py
#!/usr/bin/env python # """ These functions, when given a magnitude mag between cmin and cmax, return a colour tuple (red, green, blue). Light blue is cold (low magnitude) and yellow is hot (high magnitude). """ import math def floatRgb(mag, cmin, cmax, alpha=1.0): """ Return a tuple of floats between ...
(mag, cmin, cmax): """ Return a tuple of strings to be used in HTML documents. """ return "#%02x%02x%02x"%rgb(mag, cmin, cmax)
htmlRgb
identifier_name
colormap.py
#!/usr/bin/env python # """ These functions, when given a magnitude mag between cmin and cmax, return a colour tuple (red, green, blue). Light blue is cold (low magnitude) and yellow is hot (high magnitude). """ import math def floatRgb(mag, cmin, cmax, alpha=1.0):
def strRgb(mag, cmin, cmax): """ Return a tuple of strings to be used in Tk plots. """ red, green, blue = floatRgb(mag, cmin, cmax) return "#%02x%02x%02x" % (red*255, green*255, blue*255) def rgb(mag, cmin, cmax): """ Return a tuple of integers to be used in A...
""" Return a tuple of floats between 0 and 1 for the red, green and blue amplitudes. """ try: # normalize to [0,1] x = float(mag-cmin)/float(cmax-cmin) except: # cmax = cmin x = 0.5 blue = min((max((4*(0.75-x), 0.)), 1.))...
identifier_body