file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ast.rs | use std::cell::Cell;
use std::fmt;
use std::vec::Vec;
pub type Var = String;
pub type Atom = String;
pub enum TopLevel {
Fact(Term),
Query(Term)
}
#[derive(Clone, Copy)]
pub enum Level {
Shallow, Deep
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
mat... | match self {
&Term::Atom(_, _) | &Term::Var(_, _) => 0,
&Term::Clause(_, _, ref child_terms) => child_terms.len()
}
}
} | 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 http://mozilla.org/MPL/2.0/.
//! A library for interacting with Twitter.
//!
//! [Repository](https://github.com/QuietMisdreavus/twitter-rs)
//!
/... | //!
//! ```rust,no_run
//! # use egg_mode::Token;
//! use egg_mode::tweet::DraftTweet;
//! # #[tokio::main]
//! # async fn main() {
//! # let token: Token = unimplemented!();
//!
//! let post = DraftTweet::new("Hey Twitter!").send(&token).await.unwrap();
//! # }
//! ```
//!
//! # Types and Functions
//!
//! All of the ... | //!
//! To post a new tweet: | random_line_split |
auth.service.js | 'use strict';
angular.module('terminaaliApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
*... | }, function(err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
... | }, function(user) {
return cb(user); | random_line_split |
auth.service.js | 'use strict';
angular.module('terminaaliApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
*... |
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function() {
return currentUser.role === 'admin';
},
/**
* Get auth token
*/
getToken: function() {
return $cookieStore.get('token');
}
};
}... | {
cb(false);
} | conditional_block |
UserDirBlock.py | import time
from Block import Block
from ..ProtectFlags import ProtectFlags
class UserDirBlock(Block):
def __init__(self, blkdev, blk_num):
Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR)
def set(self, data):
self._set_data(data)
self._read()
def read(... |
# UserDir fields
self.own_key = self._get_long(1)
self.protect = self._get_long(-48)
self.comment = self._get_bstr(-46, 79)
self.mod_ts = self._get_timestamp(-23)
self.name = self._get_bstr(-20, 30)
self.hash_chain = self._get_long(-4)
self.parent = self._get_long(-3)
self.extensio... | return False | conditional_block |
UserDirBlock.py | import time
from Block import Block
from ..ProtectFlags import ProtectFlags
class UserDirBlock(Block):
def __init__(self, blkdev, blk_num):
|
def set(self, data):
self._set_data(data)
self._read()
def read(self):
self._read_data()
self._read()
def _read(self):
Block.read(self)
if not self.valid:
return False
# UserDir fields
self.own_key = self._get_long(1)
self.protect = self._get_long(-48)
self... | Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR) | identifier_body |
UserDirBlock.py | import time
from Block import Block
from ..ProtectFlags import ProtectFlags
class UserDirBlock(Block):
def __init__(self, blkdev, blk_num):
Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR)
def set(self, data):
self._set_data(data)
self._read()
def read(... | self.comment = ''
else:
self.comment = comment
# timestamps
self.mod_ts = mod_ts
self.name = name
self.hash_chain = hash_chain
self.parent = parent
self.extension = extension
# empty hash table
self.hash_table = []
self.hash_size = self.blkdev.block_longs - 56
for... | def create(self, parent, name, protect=0, comment=None, mod_ts=None, hash_chain=0, extension=0):
Block.create(self)
self.own_key = self.blk_num
self.protect = protect
if comment == None: | random_line_split |
UserDirBlock.py | import time
from Block import Block
from ..ProtectFlags import ProtectFlags
class | (Block):
def __init__(self, blkdev, blk_num):
Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR)
def set(self, data):
self._set_data(data)
self._read()
def read(self):
self._read_data()
self._read()
def _read(self):
Block.read(self)
if... | UserDirBlock | identifier_name |
twilio.js | var twilio = require('twilio');
| // REST client will handle authentication and response serialzation for you.
client.sms.messages.create({
to:'+19162218736',
from:'+12097819195',
body:'Testing text message capabilities for app!'
}, function(error, message) {
// The HTTP request to Twilio will run asynchronously. This callback
// fu... | var accountSid = 'ACd07fa19be220015c1f623bc38c1785e7';
var authToken = '78b4e06ced50c8cc150dbccbf0880ab9';
var client = new twilio.RestClient(accountSid, authToken);
// Pass in parameters to the REST API using an object literal notation. The | random_line_split |
twilio.js | var twilio = require('twilio');
var accountSid = 'ACd07fa19be220015c1f623bc38c1785e7';
var authToken = '78b4e06ced50c8cc150dbccbf0880ab9';
var client = new twilio.RestClient(accountSid, authToken);
// Pass in parameters to the REST API using an object literal notation. The
// REST client will handle authentication an... |
}); | {
console.log('Oops! There was an error.');
} | conditional_block |
brunch-config.js | exports.config = {
// See http://brunch.io/#documentation for docs.
files: {
javascripts: {
joinTo: "js/app.js"
// To use a separate vendor.js bundle, specify two files path
// https://github.com/brunch/brunch/blob/master/docs/config.md#files
// joinTo: {
// "js/app.js": /^(js)/,
... | // Do not use ES6 compiler in vendor code
ignore: [/vendor/, /node_modules/]
},
elmBrunch: {
elmFolder: "elm",
mainModules: ["Main.elm"],
makeParameters: ["--warn", "--debug"],
outputFolder: "../js"
},
sass: {
options: {
includePaths: ["node_modules/boot... | },
// Configure your plugins
plugins: {
babel: { | random_line_split |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut ac... |
#[test]
fn solution() {
let sol = Solution {};
assert_eq!(
sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")),
"BANC"
);
assert_eq!(sol.min_window(String::from(""), String::from("ABC")), "");
assert_eq!(sol.min_window(String::from(... |
#[cfg(test)]
mod tests {
use super::Solution; | random_line_split |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String |
}
pub fn hm_is_valid(target_hm: &HashMap<char, u32>, test_hm: &HashMap<char, u32>) -> bool {
if target_hm == test_hm {
return true;
}
for (c, count) in target_hm.iter() {
match test_hm.get(c) {
None => return false,
Some(test_count) if test_count < count => return ... | {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut acc, c| {
*acc.entry(c).or_insert(0) += 1;
acc
});
let s_vec: Vec<char> = s.chars().collect();
let filtered_s: Vec<(usize, char)> =... | identifier_body |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut ac... | () {
let sol = Solution {};
assert_eq!(
sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")),
"BANC"
);
assert_eq!(sol.min_window(String::from(""), String::from("ABC")), "");
assert_eq!(sol.min_window(String::from("RTY"), String::from("ABC"))... | solution | identifier_name |
slide-to-accept.ts | import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'page-slide-to-accept',
templateUrl: 'slide-to-accept.html',
})
export class SlideToAcceptPage implemen... |
public toggleAnimation(): void {
if (this.isDisabled) return;
this.animation = true;
setTimeout(() => {
this.animation = false;
}, 300);
}
}
| {
if (!boolean) {
this.resetButton();
}
} | identifier_body |
slide-to-accept.ts | import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'page-slide-to-accept',
templateUrl: 'slide-to-accept.html',
})
export class SlideToAcceptPage implemen... | this.isConfirm = false;
// Reset state variables
// Resets button position
let posCss = {
"transform": "translateX(0px)",
"-webkit-transform": "translateX(0px)"
};
this.renderer.setElementStyle(
this.htmlButtonElem,
'transform',
posCss['transfo... | // Only reset if button sliding is not done yet
if (!this.slideButtonDone || this.isDisabled) { | random_line_split |
slide-to-accept.ts | import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'page-slide-to-accept',
templateUrl: 'slide-to-accept.html',
})
export class SlideToAcceptPage implemen... |
}
isConfirmed(boolean) {
if (!boolean) {
this.resetButton();
}
}
public toggleAnimation(): void {
if (this.isDisabled) return;
this.animation = true;
setTimeout(() => {
this.animation = false;
}, 300);
}
}
| {
this.isConfirm = true;
this.slideButtonDone = false;
this.slideDone.emit(true);
} | conditional_block |
slide-to-accept.ts | import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'page-slide-to-accept',
templateUrl: 'slide-to-accept.html',
})
export class | implements AfterViewInit {
@Output() slideDone = new EventEmitter<boolean>();
@Input() buttonText: string;
@Input()
set disabled(disabled: boolean) {
this.isDisabled = (disabled !== undefined) ? disabled : false;
};
get disabled() {
return this.isDisabled;
}
@Input()
set slideButtonDone(don... | SlideToAcceptPage | identifier_name |
small-enum-range-edge.rs | // Copyright 2013 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 ... | { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8);
assert_eq!(CLu... | Eu | identifier_name |
small-enum-range-edge.rs | // Copyright 2013 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 ... | {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8);
assert_eq!(CLu as u8, Eu::Lu as u8);
assert_eq!(CHu as u8, Eu::Hu as u8);
assert_eq!(CLs as i8, Es::Ls as i8);
assert_eq!(CHs as i8, Es::Hs as i8);
} | identifier_body | |
small-enum-range-edge.rs | // Copyright 2013 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 ... | #[repr(u8)]
#[derive(Copy)]
enum Eu { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1... | */
| random_line_split |
uio.rs | //! Vectored I/O
use crate::Result;
use crate::errno::Errno;
use libc::{self, c_int, c_void, size_t, off_t};
use std::marker::PhantomData;
use std::os::unix::io::RawFd;
/// Low-level vectored write to a raw file descriptor
///
/// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.... | }, PhantomData)
}
}
impl<'a> IoVec<&'a mut [u8]> {
/// Create an `IoVec` from a mutable Rust slice.
pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> {
IoVec(libc::iovec {
iov_base: buf.as_ptr() as *mut c_void,
iov_len: buf.len() as size_t,
}, P... | iov_base: buf.as_ptr() as *mut c_void,
iov_len: buf.len() as size_t, | random_line_split |
uio.rs | //! Vectored I/O
use crate::Result;
use crate::errno::Errno;
use libc::{self, c_int, c_void, size_t, off_t};
use std::marker::PhantomData;
use std::os::unix::io::RawFd;
/// Low-level vectored write to a raw file descriptor
///
/// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.... | (fd: RawFd, iov: &[IoVec<&[u8]>],
offset: off_t) -> Result<usize> {
#[cfg(target_env = "uclibc")]
let offset = offset as libc::off64_t; // uclibc doesn't use off_t
let res = unsafe {
libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset)
};
Errno::r... | pwritev | identifier_name |
test_logger.py | from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
|
def test_pprint_with_indent():
"""Test pprint_with_indent does indentation."""
out = StringIO()
data = {
12: 34,
'confirm_password': '12345qwerty',
'credentials': ['abc', 'def'],
'key': 'value',
'nested_dict': {'password': 'not_filtered'},
'password': '1234... | """Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) == 123
# But does redact sensitive keys
assert filtered_value('password', '123pass') != '123pass'
# The returned value is an object... | identifier_body |
test_logger.py | from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
"""Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) =... | 12: 34,
'confirm_password': '12345qwerty',
'credentials': ['abc', 'def'],
'key': 'value',
'nested_dict': {'password': 'not_filtered'},
'password': '12345qwerty',
}
pprint_with_indent(data, out)
assert (
out.getvalue()
== '''\
{12: 34,
... | random_line_split | |
test_logger.py | from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
"""Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) =... | ():
"""Test pprint_with_indent does indentation."""
out = StringIO()
data = {
12: 34,
'confirm_password': '12345qwerty',
'credentials': ['abc', 'def'],
'key': 'value',
'nested_dict': {'password': 'not_filtered'},
'password': '12345qwerty',
}
pprint_wit... | test_pprint_with_indent | identifier_name |
main.js | /*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initializ... |
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dat... | {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
... | conditional_block |
main.js | /*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initializ... | // Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.te... | maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
}); | random_line_split |
getGeneDescLocal_Illumina.py | import pandas as pd
def closeFunc():
|
def oligosList():
oligosPath = input('Path to the file containing the list of probes: ')
oligos = open(oligosPath)
oligos = oligos.readlines()
oligosList = []
for oligo in oligos:
item = oligo.strip()
oligosList.append(item)
return oligosList
def main(oligosList, fullData = ... | print('''Type 'quit' and press enter to exit program''')
answer = input(': ')
if answer == 'quit':
quit()
else:
closeFunc() | identifier_body |
getGeneDescLocal_Illumina.py | import pandas as pd
def closeFunc():
print('''Type 'quit' and press enter to exit program''')
answer = input(': ')
if answer == 'quit':
quit()
else:
closeFunc()
def | ():
oligosPath = input('Path to the file containing the list of probes: ')
oligos = open(oligosPath)
oligos = oligos.readlines()
oligosList = []
for oligo in oligos:
item = oligo.strip()
oligosList.append(item)
return oligosList
def main(oligosList, fullData = False):
db =... | oligosList | identifier_name |
getGeneDescLocal_Illumina.py | import pandas as pd
def closeFunc():
print('''Type 'quit' and press enter to exit program''')
answer = input(': ')
if answer == 'quit':
quit()
else:
closeFunc()
def oligosList():
oligosPath = input('Path to the file containing the list of probes: ')
oligos = open(oligosPath)
... |
elif answer == 'yes':
main(oligosList, True)
else:
print('Wrong answer')
closeFunc() | main(oligosList) | conditional_block |
getGeneDescLocal_Illumina.py | import pandas as pd
def closeFunc():
print('''Type 'quit' and press enter to exit program''')
answer = input(': ')
if answer == 'quit':
quit()
else:
closeFunc()
def oligosList():
oligosPath = input('Path to the file containing the list of probes: ')
oligos = open(oligosPath)
... |
if __name__ == "__main__":
oligosList = oligosList()
answer = input('Do you want full data? (yes/no) ')
if answer == 'no':
main(oligosList)
elif answer == 'yes':
main(oligosList, True)
else:
print('Wrong answer')
closeFunc() | closeFunc() | random_line_split |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | mod core;
mod externs;
mod interning;
mod intrinsics;
mod nodes;
mod scheduler;
mod selectors;
mod session;
mod tasks;
mod types;
pub use crate::context::{Core, ExecutionStrategyOptions, RemotingOptions};
pub use crate::core::{Failure, Function, Key, Params, TypeId, Value};
pub use crate::intrinsics::Intrinsics;
pub u... | mod context; | random_line_split |
pending.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* 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 Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... | (&self, hardware: Hardware) -> bool {
let interrupt = hardware as u8;
self.0 & (0b1 << interrupt) != 0
}
}
impl ICPR {
pub fn clear_pending(&mut self, hardware: Hardware) {
let interrupt = hardware as u8;
self.0 |= 0b1 << interrupt;
}
}
#[cfg(test)]
mod tests {
use su... | interrupt_is_pending | identifier_name |
pending.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* 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 Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... |
}
impl ICPR {
pub fn clear_pending(&mut self, hardware: Hardware) {
let interrupt = hardware as u8;
self.0 |= 0b1 << interrupt;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ispr_set_pending() {
let mut ispr = ISPR(0);
ispr.set_pending(Hardware::Fla... | {
let interrupt = hardware as u8;
self.0 & (0b1 << interrupt) != 0
} | identifier_body |
pending.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* 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 Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... | }
impl ICPR {
pub fn clear_pending(&mut self, hardware: Hardware) {
let interrupt = hardware as u8;
self.0 |= 0b1 << interrupt;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ispr_set_pending() {
let mut ispr = ISPR(0);
ispr.set_pending(Hardware::Flas... | let interrupt = hardware as u8;
self.0 & (0b1 << interrupt) != 0
} | random_line_split |
gas_schedule.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module lays out the basic abstract costing schedule for bytecode instructions.
//!
//! It is important to note that the cost schedule defined in this file does not track hashing
//! operations or other native operations; the co... | (instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self {
Self {
instruction_gas: InternalGasUnits::new(instr_gas),
memory_gas: InternalGasUnits::new(mem_gas),
}
}
/// Convert a GasCost to a total gas charge in `InternalGasUnits`.
#[inline]
pub fn total(&self) -> In... | new | identifier_name |
gas_schedule.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module lays out the basic abstract costing schedule for bytecode instructions.
//!
//! It is important to note that the cost schedule defined in this file does not track hashing
//! operations or other native operations; the co... | doc: "Units of gas as seen by clients of the Move VM."
}
define_gas_unit! {
name: InternalGasUnits,
carrier: GasCarrier,
doc: "Units of gas used within the Move VM, scaled for fine-grained accounting."
}
define_gas_unit! {
name: GasPrice,
carrier: GasCarrier,
doc: "A newtype wrapper around... |
define_gas_unit! {
name: GasUnits,
carrier: GasCarrier, | random_line_split |
gas_schedule.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module lays out the basic abstract costing schedule for bytecode instructions.
//!
//! It is important to note that the cost schedule defined in this file does not track hashing
//! operations or other native operations; the co... |
/// Subtract one `GasAlgebra` from the other.
fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self {
self.map2(right, Sub::sub)
}
/// Multiply two `GasAlgebra`s together.
fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self {
self.map2(right, Mul::mul)
}
/// Divid... | {
self.map2(right, Add::add)
} | identifier_body |
list-view.ts | import Service from '@ember/service';
import Store from '@ember-data/store';
import FieldInformationService from '@getflights/ember-field-components/services/field-information';
import { inject as service } from '@ember/service';
import { assert } from '@ember/debug';
import { isBlank } from '@ember/utils';
import List... | (
modelName: string,
routeName: string
): string | number {
const listViewSelections = this.storage.get('listViewSelections');
let selection = 'All';
if (
!isBlank(listViewSelections) &&
listViewSelections.hasOwnProperty(routeName) &&
listViewSelections[routeName].hasOwnProperty... | getActiveListViewForRoute | identifier_name |
list-view.ts | import Service from '@ember/service';
import Store from '@ember-data/store';
import FieldInformationService from '@getflights/ember-field-components/services/field-information';
import { inject as service } from '@ember/service';
import { assert } from '@ember/debug';
import { isBlank } from '@ember/utils';
import List... | * @param route the route
*/
setListViewSelectionForRoute(
modelName: string,
selection: number | string,
route: string
): void {
let listViewSelections = this.storage.get('listViewSelections');
if (isBlank(listViewSelections)) {
listViewSelections = {};
}
if (!listViewSelec... | * @param modelName The model name
* @param selection the new selection | random_line_split |
list-view.ts | import Service from '@ember/service';
import Store from '@ember-data/store';
import FieldInformationService from '@getflights/ember-field-components/services/field-information';
import { inject as service } from '@ember/service';
import { assert } from '@ember/debug';
import { isBlank } from '@ember/utils';
import List... |
return selection;
}
/**
* Sets the list view for the current route
*/
setListViewSelectionForCurrentRoute(
modelName: string,
selection: number | string
): void {
this.setListViewSelectionForRoute(
modelName,
selection,
this.router.currentRouteName
);
}
/**
... | {
selection = listViewSelections[routeName][modelName];
} | conditional_block |
list-view.ts | import Service from '@ember/service';
import Store from '@ember-data/store';
import FieldInformationService from '@getflights/ember-field-components/services/field-information';
import { inject as service } from '@ember/service';
import { assert } from '@ember/debug';
import { isBlank } from '@ember/utils';
import List... |
/**
* Returns the active list view for the current route
*/
getActiveListViewForCurrentRoute(modelName: string): ListViewInterface {
const key = this.getActiveListViewKeyForCurrentRoute(modelName);
return this.getListViewByKey(modelName, key);
}
/**
* Returns the list view that should be sel... | {
const modelClass = this.fieldInformation.getModelClass(modelName);
assert(
`No list view (${listViewName}) defined on the modelclass ${modelName}`,
modelClass.hasOwnProperty('settings') &&
modelClass.settings.hasOwnProperty('listViews') &&
modelClass.settings.listViews.hasOwnPrope... | identifier_body |
async_test.py | # import asyncio
#
# async def compute(x, y):
# print("Compute %s + %s ..." % (x, y))
# await asyncio.sleep(1.0)
# return x + y
# | # for i in range(10):
# result = await compute(x, y)
# print("%s + %s = %s" % (x, y, result))
#
# loop = asyncio.get_event_loop()
# loop.run_until_complete(print_sum(1,2))
# asyncio.ensure_future(print_sum(1, 2))
# asyncio.ensure_future(print_sum(3, 4))
# asyncio.ensure_future(print_sum(5, 6))
# l... | # async def print_sum(x, y): | random_line_split |
async_test.py | # import asyncio
#
# async def compute(x, y):
# print("Compute %s + %s ..." % (x, y))
# await asyncio.sleep(1.0)
# return x + y
#
# async def print_sum(x, y):
# for i in range(10):
# result = await compute(x, y)
# print("%s + %s = %s" % (x, y, result))
#
# loop = asyncio.get_event_loop()... | (who, num):
i = 0
while True:
if i > num:
return
print('{}: Before loop {}'.format(who, i))
await asyncio.sleep(1)
i += 1
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date('AAA', 4))
asyncio.ensure_future(display_date('BBB', 6))
loop.run_forever()
| display_date | identifier_name |
async_test.py | # import asyncio
#
# async def compute(x, y):
# print("Compute %s + %s ..." % (x, y))
# await asyncio.sleep(1.0)
# return x + y
#
# async def print_sum(x, y):
# for i in range(10):
# result = await compute(x, y)
# print("%s + %s = %s" % (x, y, result))
#
# loop = asyncio.get_event_loop()... |
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date('AAA', 4))
asyncio.ensure_future(display_date('BBB', 6))
loop.run_forever()
| i = 0
while True:
if i > num:
return
print('{}: Before loop {}'.format(who, i))
await asyncio.sleep(1)
i += 1 | identifier_body |
async_test.py | # import asyncio
#
# async def compute(x, y):
# print("Compute %s + %s ..." % (x, y))
# await asyncio.sleep(1.0)
# return x + y
#
# async def print_sum(x, y):
# for i in range(10):
# result = await compute(x, y)
# print("%s + %s = %s" % (x, y, result))
#
# loop = asyncio.get_event_loop()... |
print('{}: Before loop {}'.format(who, i))
await asyncio.sleep(1)
i += 1
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date('AAA', 4))
asyncio.ensure_future(display_date('BBB', 6))
loop.run_forever()
| return | conditional_block |
per_worker_gaussian_noise.py | from gym.spaces import Space
from typing import Optional
from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise
from ray.rllib.utils.schedules import ConstantSchedule
class PerWorkerGaussianNoise(GaussianNoise):
"""A per-worker Gaussian noise class for distributed algorithms.
Sets the `scale` ... | (self, action_space: Space, *, framework: Optional[str],
num_workers: Optional[int], worker_index: Optional[int],
**kwargs):
"""
Args:
action_space (Space): The gym action space used by the environment.
num_workers (Optional[int]): The overall nu... | __init__ | identifier_name |
per_worker_gaussian_noise.py | from gym.spaces import Space
from typing import Optional
from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise
from ray.rllib.utils.schedules import ConstantSchedule
class PerWorkerGaussianNoise(GaussianNoise):
| """A per-worker Gaussian noise class for distributed algorithms.
Sets the `scale` schedules of individual workers to a constant:
0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7)
See Ape-X paper.
"""
def __init__(self, action_space: Space, *, framework: Optional[str],
num_... | identifier_body | |
per_worker_gaussian_noise.py | from gym.spaces import Space
from typing import Optional
from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise
from ray.rllib.utils.schedules import ConstantSchedule
class PerWorkerGaussianNoise(GaussianNoise): | See Ape-X paper.
"""
def __init__(self, action_space: Space, *, framework: Optional[str],
num_workers: Optional[int], worker_index: Optional[int],
**kwargs):
"""
Args:
action_space (Space): The gym action space used by the environment.
... | """A per-worker Gaussian noise class for distributed algorithms.
Sets the `scale` schedules of individual workers to a constant:
0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) | random_line_split |
per_worker_gaussian_noise.py | from gym.spaces import Space
from typing import Optional
from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise
from ray.rllib.utils.schedules import ConstantSchedule
class PerWorkerGaussianNoise(GaussianNoise):
"""A per-worker Gaussian noise class for distributed algorithms.
Sets the `scale` ... |
# Local worker should have zero exploration so that eval
# rollouts run properly.
else:
scale_schedule = ConstantSchedule(0.0, framework=framework)
super().__init__(
action_space,
scale_schedule=scale_schedule,
framework=f... | num_workers_minus_1 = float(num_workers - 1) \
if num_workers > 1 else 1.0
exponent = (1 + (worker_index / num_workers_minus_1) * 7)
scale_schedule = ConstantSchedule(
0.4**exponent, framework=framework) | conditional_block |
results.py | """
query or callproc Results
"""
import logging
import psycopg2
LOGGER = logging.getLogger(__name__)
class Results(object):
"""The :py:class:`Results` class contains the results returned from
:py:meth:`Session.query <queries.Session.query>` and
:py:meth:`Session.callproc <queries.Session.callproc>`. It... |
def __bool__(self):
return self.__nonzero__()
def __repr__(self):
return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self))
def as_dict(self):
"""Return a single row result as a dictionary. If the results contain
multiple rows, a :py:class:`ValueError` will be ... | return bool(self.cursor.rowcount) | identifier_body |
results.py | """
query or callproc Results
"""
import logging
import psycopg2
LOGGER = logging.getLogger(__name__)
class Results(object):
"""The :py:class:`Results` class contains the results returned from
:py:meth:`Session.query <queries.Session.query>` and
:py:meth:`Session.callproc <queries.Session.callproc>`. It... |
def __len__(self):
"""Return the number of rows that were returned from the query
:rtype: int
"""
return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0
def __nonzero__(self):
return bool(self.cursor.rowcount)
def __bool__(self):
return self.__n... | self._rewind()
for row in self.cursor:
yield row | conditional_block |
results.py | """
query or callproc Results
"""
import logging
import psycopg2
LOGGER = logging.getLogger(__name__)
class Results(object):
"""The :py:class:`Results` class contains the results returned from
:py:meth:`Session.query <queries.Session.query>` and
:py:meth:`Session.callproc <queries.Session.callproc>`. It... | """Return the status message returned by PostgreSQL after the query
was executed.
:rtype: str
"""
return self.cursor.statusmessage
def _rewind(self):
"""Rewind the cursor to the first row"""
self.cursor.scroll(0, 'absolute') | return self.cursor.query
@property
def status(self): | random_line_split |
results.py | """
query or callproc Results
"""
import logging
import psycopg2
LOGGER = logging.getLogger(__name__)
class Results(object):
"""The :py:class:`Results` class contains the results returned from
:py:meth:`Session.query <queries.Session.query>` and
:py:meth:`Session.callproc <queries.Session.callproc>`. It... | (self):
"""Return the status message returned by PostgreSQL after the query
was executed.
:rtype: str
"""
return self.cursor.statusmessage
def _rewind(self):
"""Rewind the cursor to the first row"""
self.cursor.scroll(0, 'absolute')
| status | identifier_name |
utils.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactoryResolver, Injector, Type} from '@angular/core';
/**
* Provide methods for scheduling the exe... | (taskFn: () => void, delay: number): () => void {
const id = setTimeout(taskFn, delay);
return () => clearTimeout(id);
},
/**
* Schedule a callback to be called before the next render.
* (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.)
*
* Returns a fu... | schedule | identifier_name |
utils.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactoryResolver, Injector, Type} from '@angular/core';
/**
* Provide methods for scheduling the exe... |
return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false;
}
/**
* Test two values for strict equality, accounting for the fact that `NaN !== NaN`.
*/
export function strictEquals(value1: any, value2: any): boolean {
return value1 === value2 || (value1 !== value1 && value2 !== value2);
}
/... | {
const elProto = <any>Element.prototype;
_matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;
} | conditional_block |
utils.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactoryResolver, Injector, Type} from '@angular/core';
/**
* Provide methods for scheduling the exe... | return typeof value === 'function';
}
/**
* Convert a kebab-cased string to camelCased.
*/
export function kebabToCamelCase(input: string): string {
return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase());
}
let _matches: (this: any, selector: string) => boolean;
/**
* Check whether an `Element` ... | */
export function isFunction(value: any): value is Function { | random_line_split |
utils.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactoryResolver, Injector, Type} from '@angular/core';
/**
* Provide methods for scheduling the exe... |
/**
* Convert a kebab-cased string to camelCased.
*/
export function kebabToCamelCase(input: string): string {
return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase());
}
let _matches: (this: any, selector: string) => boolean;
/**
* Check whether an `Element` matches a CSS selector.
* NOTE: this i... | {
return typeof value === 'function';
} | identifier_body |
construct.py | """Functions to construct sparse matrices
"""
__docformat__ = "restructuredtext en"
__all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand']
from warnings import warn
import numpy as np
from sputils import upcast
from csr import csr_matrix
from csc import csc_m... |
elif format == 'dia':
data = np.ones(n, dtype=dtype)
diags = [0]
return dia_matrix((data,diags), shape=(n,n))
else:
return identity(n, dtype=dtype, format='csr').asformat(format)
def eye(m, n, k=0, dtype='d', format=None):
"""eye(m, n) returns a sparse (m x n) matrix where... | row = np.arange(n, dtype=np.intc)
col = np.arange(n, dtype=np.intc)
data = np.ones(n, dtype=dtype)
return coo_matrix((data,(row,col)),(n,n)) | conditional_block |
construct.py | """Functions to construct sparse matrices
"""
__docformat__ = "restructuredtext en"
__all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand']
from warnings import warn
import numpy as np
from sputils import upcast
from csr import csr_matrix
from csc import csc_m... |
def rand(m, n, density=0.01, format="coo", dtype=None):
"""Generate a sparse matrix of the given shape and density with uniformely
distributed values.
Parameters
----------
m, n: int
shape of the matrix
density: real
density of the generated matrix: density equal to one means ... | """
Build a sparse matrix from sparse sub-blocks
Parameters
----------
blocks
grid of sparse matrices with compatible shapes
an entry of None implies an all-zero matrix
format : sparse format of the result (e.g. "csr")
by default an appropriate sparse matrix format is return... | identifier_body |
construct.py | """Functions to construct sparse matrices
"""
__docformat__ = "restructuredtext en"
__all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand']
from warnings import warn
import numpy as np
from sputils import upcast
from csr import csr_matrix
from csc import csc_m... | (n, dtype='d', format=None):
"""Identity matrix in sparse format
Returns an identity matrix with shape (n,n) using a given
sparse format and dtype.
Parameters
----------
n : integer
Shape of the identity matrix.
dtype :
Data type of the matrix
format : string
Sp... | identity | identifier_name |
construct.py | """Functions to construct sparse matrices
"""
__docformat__ = "restructuredtext en"
__all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand']
from warnings import warn
import numpy as np
from sputils import upcast
from csr import csr_matrix
from csc import csc_m... | -------
kronecker sum in a sparse matrix format
Examples
--------
"""
A = coo_matrix(A)
B = coo_matrix(B)
if A.shape[0] != A.shape[1]:
raise ValueError('A is not square')
if B.shape[0] != B.shape[1]:
raise ValueError('B is not square')
dtype = upcast(A.dtype... |
Returns | random_line_split |
StepLabel.d.ts | import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { InternalStandardProps as StandardProps } from '..';
import { StepIconProps } from '../StepIcon';
import { Theme } from '../styles';
import { StepLabelClasses } from './stepLabelClasses';
export interface StepLabelProps extends Stan... | * @default false
*/
error?: boolean;
/**
* Override the default label of the step icon.
*/
icon?: React.ReactNode;
/**
* The optional node to display.
*/
optional?: React.ReactNode;
/**
* The component to render in place of the [`StepIcon`](/api/step-icon/).
*/
StepIconComponent?: ... | classes?: Partial<StepLabelClasses>;
/**
* If `true`, the step is marked as failed. | random_line_split |
setup.py | import os
from setuptools import setup
from setuptools import find_packages
version_file = 'VERSION.txt'
version = open(version_file).read().strip()
description_file = 'README.txt'
description = open(description_file).read().split('\n\n')[0].strip()
description = description.replace('\n', ' ')
long_description_file =... | 'console_scripts': ('ximenez=ximenez.xim:main', )
},
author='Damien Baty',
author_email='damien.baty@remove-me.gmail.com',
description=description,
long_description=long_description,
license='GNU GPL',
classifiers=['Development Status :: 4 - Beta',
'Intended Aud... | zip_safe=False,
entry_points={ | random_line_split |
effects.pulsate.js | /*
* jQuery UI Effects Pulsate 1.7.2
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Pulsate
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.pulsate = functio... | el.animate({opacity: 1}, duration, o.options.easing);
times = times-2;
}
// Animate
for (var i = 0; i < times; i++) { // Pulsate
el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing);
};
if (mode == 'hide') { // Last Pulse
el.animate({opacity: 0}, ... | if (el.is(':hidden')) { // Show fadeIn
el.css('opacity', 0);
el.show(); // Show | random_line_split |
icon.rs | use image::{Rgba, RgbaImage};
use imageproc::drawing::draw_text_mut;
use image::imageops::resize;
use rusttype::{Scale, Font};
use std::ptr::null_mut;
use std::collections::HashMap;
pub type GeneratedIcon = *mut winapi::shared::windef::HICON__;
pub struct IconGenerator {
icon_cache: HashMap<u8, GeneratedIcon>,
}... |
fn scale_params(n: usize) -> ((u32, u32), Scale) {
match n {
1 => {
((24, 0), Scale { x: 128.0, y: 128.0 })
}
2 => {
((0, 0), Scale { x: 120.0, y: 120.0 })
}
_ => {
((0, 20), Scale { x: 80.0, y: 80.... | {
if self.icon_cache.contains_key(&value) && value != 0 {
return self.icon_cache[&value];
} else {
let new_icon = IconGenerator::create_icon(value);
self.icon_cache.insert(value, new_icon);
new_icon
}
} | identifier_body |
icon.rs | use image::{Rgba, RgbaImage};
use imageproc::drawing::draw_text_mut;
use image::imageops::resize;
use rusttype::{Scale, Font};
use std::ptr::null_mut;
use std::collections::HashMap;
pub type GeneratedIcon = *mut winapi::shared::windef::HICON__;
pub struct IconGenerator {
icon_cache: HashMap<u8, GeneratedIcon>,
}... | }
_ => {
((0, 20), Scale { x: 80.0, y: 80.0 })
}
}
}
fn create_icon(value: u8) -> GeneratedIcon {
let value_to_draw = value.to_string();
let mut image = RgbaImage::new(128, 128);
let font = Font::try_from_bytes(include_bytes!... | ((0, 0), Scale { x: 120.0, y: 120.0 }) | random_line_split |
icon.rs | use image::{Rgba, RgbaImage};
use imageproc::drawing::draw_text_mut;
use image::imageops::resize;
use rusttype::{Scale, Font};
use std::ptr::null_mut;
use std::collections::HashMap;
pub type GeneratedIcon = *mut winapi::shared::windef::HICON__;
pub struct IconGenerator {
icon_cache: HashMap<u8, GeneratedIcon>,
}... | (&mut self, value: u8) -> GeneratedIcon {
if self.icon_cache.contains_key(&value) && value != 0 {
return self.icon_cache[&value];
} else {
let new_icon = IconGenerator::create_icon(value);
self.icon_cache.insert(value, new_icon);
new_icon
}
}... | generate | identifier_name |
ResliceBSpline.py | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# this script tests vtkImageReslice with different interpolation modes,
# with the wrap-pad feature turned on and with a rotation
# Image pipeline
reader = vtk.vtkImageReader()
reader... | mapper4.SetInputConnection(reslice4.GetOutputPort())
mapper4.SetColorWindow(2000)
mapper4.SetColorLevel(1000)
mapper4.SetZSlice(0)
actor1 = vtk.vtkActor2D()
actor1.SetMapper(mapper1)
actor2 = vtk.vtkActor2D()
actor2.SetMapper(mapper2)
actor3 = vtk.vtkActor2D()
actor3.SetMapper(mapper3)
actor4 = vtk.vtkActor2D()
actor4.... | mapper3.SetZSlice(0)
mapper4 = vtk.vtkImageMapper() | random_line_split |
userFilter.ts | import { SyncService } from '../storage/sync.service';
import { D1ItemUserReview } from '../item-review/d1-dtr-api-types';
import { D2ItemUserReview } from '../item-review/d2-dtr-api-types';
/**
* Note a problem user's membership ID so that we can ignore their reviews in the future.
* Persists the list of ignored us... | () {
const ignoredUsersKey = 'ignoredUsers';
return SyncService.get().then((data) => data[ignoredUsersKey] || []);
}
| getIgnoredUsers | identifier_name |
userFilter.ts | import { SyncService } from '../storage/sync.service';
import { D1ItemUserReview } from '../item-review/d1-dtr-api-types';
import { D2ItemUserReview } from '../item-review/d2-dtr-api-types';
/**
* Note a problem user's membership ID so that we can ignore their reviews in the future.
* Persists the list of ignored us... | } |
function getIgnoredUsers() {
const ignoredUsersKey = 'ignoredUsers';
return SyncService.get().then((data) => data[ignoredUsersKey] || []); | random_line_split |
userFilter.ts | import { SyncService } from '../storage/sync.service';
import { D1ItemUserReview } from '../item-review/d1-dtr-api-types';
import { D2ItemUserReview } from '../item-review/d2-dtr-api-types';
/**
* Note a problem user's membership ID so that we can ignore their reviews in the future.
* Persists the list of ignored us... |
function getIgnoredUsers() {
const ignoredUsersKey = 'ignoredUsers';
return SyncService.get().then((data) => data[ignoredUsersKey] || []);
}
| {
return SyncService.set({ ignoredUsers: [] });
} | identifier_body |
Link.tsx | import { h, Component, prop } from 'skatejs';
import { ColorType, cssClassForColorType } from '../_helpers/colorTypes';
import style from './Link.scss';
import { css } from '../_helpers/css';
const LinkTargets = {
_self: '_self',
_blank: '_blank',
_parent: '_parent',
_top: '_top',
};
interface LinkProps { | hreflang?: string,
rel?: string,
target?: keyof typeof LinkTargets | string,
type?: string,
color?: ColorType,
}
export class Link extends Component<LinkProps> {
static get is() { return 'bl-link'; }
static get props() {
return {
href: prop.string( {
attribute: true
} ),
d... | href?: string,
download?: string, | random_line_split |
Link.tsx | import { h, Component, prop } from 'skatejs';
import { ColorType, cssClassForColorType } from '../_helpers/colorTypes';
import style from './Link.scss';
import { css } from '../_helpers/css';
const LinkTargets = {
_self: '_self',
_blank: '_blank',
_parent: '_parent',
_top: '_top',
};
interface LinkProps {
h... | () {
return {
href: prop.string( {
attribute: true
} ),
download: prop.string( {
attribute: true
} ),
hreflang: prop.string( {
attribute: true
} ),
referrerpolicy: prop.string( {
attribute: true
} ),
rel: prop.string( {
at... | props | identifier_name |
Link.tsx | import { h, Component, prop } from 'skatejs';
import { ColorType, cssClassForColorType } from '../_helpers/colorTypes';
import style from './Link.scss';
import { css } from '../_helpers/css';
const LinkTargets = {
_self: '_self',
_blank: '_blank',
_parent: '_parent',
_top: '_top',
};
interface LinkProps {
h... |
href: string;
download: string;
hreflang: string;
rel: string;
target: string;
type: string;
color: ColorType;
renderCallback() {
const { href, download, hreflang, rel, target, type, color } = this;
const colorClass = cssClassForColorType( 'c-link', color );
const className = css( 'c-lin... | {
return {
href: prop.string( {
attribute: true
} ),
download: prop.string( {
attribute: true
} ),
hreflang: prop.string( {
attribute: true
} ),
referrerpolicy: prop.string( {
attribute: true
} ),
rel: prop.string( {
attri... | identifier_body |
vz-projector.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
ds.mergeMetadata(spriteAndMetadata);
this.dataPanel.setNormalizeData(this.normalizeData);
this.setCurrentDataSet(this.originalDataSet.getSubset());
this.inspectorPanel.datasetChanged();
this.inspectorPanel.metadataChanged(spriteAndMetadata);
this.projectionsPanel.metadataChanged(spriteAndMetad... | {
let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points);
spriteAndMetadata.pointsInfo = pointsInfo;
spriteAndMetadata.stats = stats;
} | conditional_block |
vz-projector.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
notifyProjectionsUpdated() {
this.updateScatterPlotPositions();
this.scatterPlot.render();
}
/**
* Gets the current view of the embedding and saves it as a State object.
*/
getCurrentState(): State {
const state = new State();
// Save the individual datapoint projections.
state.pro... | {
this.selectedProjection = projection;
this.selectedProjectionPointAccessors = pointAccessors;
this.scatterPlot.setDimensions(dimensionality);
if (this.dataSet.projectionCanBeRendered(projection)) {
this.updateScatterPlotAttributes();
this.notifyProjectionsUpdated();
}
this.scatte... | identifier_body |
vz-projector.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | (colorOption: ColorOption):
(index: number) => string {
if ((colorOption == null) || (colorOption.map == null)) {
return null;
}
const colorer = (i: number) => {
let value =
this.dataSet.points[i].metadata[this.selectedColorOption.name];
if (value == null) {
return ... | getLegendPointColorer | identifier_name |
vz-projector.ts | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | let selectModeButton = this.querySelector('#selectMode');
selectModeButton.addEventListener('click', (event) => {
this.scatterPlot.setMode(
(selectModeButton as any).active ? Mode.SELECT : Mode.HOVER);
});
let nightModeButton = this.querySelector('#nightDayMode');
nightModeButton.add... | this.scatterPlot.startOrbitAnimation();
});
| random_line_split |
index.d.ts | declare const figureSet: {
readonly tick: string;
readonly cross: string;
readonly star: string;
readonly square: string;
readonly squareSmall: string;
readonly squareSmallFilled: string;
readonly play: string;
readonly circle: string;
readonly circleFilled: string;
readonly circleDotted: string;
readonly ci... | type FigureSet = typeof figureSet
declare const figures: {
/**
Replace Unicode symbols depending on the OS.
@param string - String where the Unicode symbols will be replaced with fallback symbols depending on the OS.
@returns The input with replaced fallback Unicode symbols on Windows.
@example
```
import fig... | random_line_split | |
test_migration.py | import unittest
import os
from unittest.mock import patch
import migration
from configuration import Builder
import configuration
from tests import testhelper
class MigrationTestCase(unittest.TestCase):
def setUp(self):
self.rootfolder = os.path.dirname(os.path.realpath(__file__)) | @patch('migration.Commiter')
@patch('migration.Initializer')
@patch('migration.RTCInitializer')
@patch('migration.os')
@patch('configuration.shutil')
def testDeletionOfLogFolderOnInitalization(self, shutil_mock, os_mock, rtc_initializer_mock, git_initializer_mock,
... | random_line_split | |
test_migration.py | import unittest
import os
from unittest.mock import patch
import migration
from configuration import Builder
import configuration
from tests import testhelper
class MigrationTestCase(unittest.TestCase):
def setUp(self):
|
@patch('migration.Commiter')
@patch('migration.Initializer')
@patch('migration.RTCInitializer')
@patch('migration.os')
@patch('configuration.shutil')
def testDeletionOfLogFolderOnInitalization(self, shutil_mock, os_mock, rtc_initializer_mock, git_initializer_mock,
... | self.rootfolder = os.path.dirname(os.path.realpath(__file__)) | identifier_body |
test_migration.py | import unittest
import os
from unittest.mock import patch
import migration
from configuration import Builder
import configuration
from tests import testhelper
class | (unittest.TestCase):
def setUp(self):
self.rootfolder = os.path.dirname(os.path.realpath(__file__))
@patch('migration.Commiter')
@patch('migration.Initializer')
@patch('migration.RTCInitializer')
@patch('migration.os')
@patch('configuration.shutil')
def testDeletionOfLogFolderOnInit... | MigrationTestCase | identifier_name |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use crate::values::{Either, N... | <L> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(#[css(if_empty = "none", iterable)] Vec<L>),
/// `context-value`
ContextValue,
}
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(
Animate,
Clone,
ComputeS... | SVGStrokeDashArray | identifier_name |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use crate::values::{Either, N... |
} else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) {
Ok(SVGPaint {
kind: SVGPaintKind::Color(color),
fallback: None,
})
} else {
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
}
/... | {
Ok(SVGPaint {
kind: kind,
fallback: parse_fallback(context, input),
})
} | conditional_block |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use crate::values::{Either, N... | MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub enum SVGLength<L> {
/// `<length> | <percentage> | <number>`
LengthPercentage(L),
/// `context-value`
#[animation(error)]
Context... | ComputeSquaredDistance,
Copy,
Debug, | random_line_split |
overloaded-autoderef-count.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 ... | struct DerefCounter<T> {
count_imm: Cell<uint>,
count_mut: uint,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn counts(&self) -> (uint, uint... | use std::ops::{Deref, DerefMut};
#[deriving(PartialEq)] | random_line_split |
overloaded-autoderef-count.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> &T {
self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
#[deriving(PartialEq, Show)]
struct Point {
x: int,
y: int
}
impl Po... | deref | identifier_name |
lpo.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later ver... | else if s.is_function() && t.is_variable() {
s.occurs_proper(t)
} else {
false
}
}
/// Checks if s is greater than or equal to t according to the ordering.
pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool {
s == t || lpo_gt(precedence, s, t)
}
fn lexical_ordering(precede... | {
if s.iter().any(|arg| lpo_ge(precedence, arg, t)) {
true
} else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) {
if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) {
true
} else {
precedence.gt(s, t)
}
... | conditional_block |
lpo.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later ver... | () {
let precedence = Precedence::default();
let x = Term::new_variable(-1);
let f_x = Term::new_function(1, vec![x.clone()]);
assert!(lpo_gt(&precedence, &f_x, &x));
assert!(!lpo_gt(&precedence, &x, &f_x));
}
#[test]
fn lpo_gt_3() {
let precedence = Preceden... | lpo_gt_2 | identifier_name |
lpo.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later ver... |
#[test]
fn lpo_gt_4() {
let precedence = Precedence::default();
let x = Term::new_variable(-1);
let f_x = Term::new_function(1, vec![x.clone()]);
let f_f_x = Term::new_function(1, vec![f_x.clone()]);
assert!(lpo_gt(&precedence, &f_f_x, &f_x));
assert!(!lpo_gt(&pr... | assert!(!lpo_gt(&precedence, &f_y, &x));
assert!(!lpo_gt(&precedence, &x, &f_y));
} | random_line_split |
lpo.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later ver... |
fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool {
assert_eq!(s.get_id(), t.get_id());
assert_eq!(s.get_arity(), t.get_arity());
for i in 0..s.get_arity() {
if lpo_gt(precedence, &s[i], &t[i]) {
return true;
} else if s[i] != t[i] {
return f... | {
s == t || lpo_gt(precedence, s, t)
} | identifier_body |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard';
import { CommunityDetailsComponent, CommunityComponent } from './community';
import { ArtifactDetailsComponent, ArtifactComponent } from './artifact';
@NgModule({
imports: [
... | { }
| AppRoutingModule | identifier_name |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard';
import { CommunityDetailsComponent, CommunityComponent } from './community';
import { ArtifactDetailsComponent, ArtifactComponent } from './artifact';
@NgModule({
imports: [
... | path: 'dashboard',
component: DashboardComponent
},
{
path: 'members',
loadChildren: './member/member.module#MemberModule'
},
{
path: 'communities',
component: CommunityCompone... | },
{ | random_line_split |
data_loader.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/. */
use crate::fetch;
use headers_core::HeaderMapExt;
use headers_ext::ContentType;
use hyper_serde::Serde;
use mime:... | () {
assert_parse(
"data:text/plain;charset=latin1,hello",
Some(ContentType::from(
"text/plain; charset=latin1".parse::<Mime>().unwrap(),
)),
Some("latin1"),
Some(b"hello"),
);
}
#[test]
fn plain_only_charset() {
assert_parse(
"data:;charset=utf-8... | plain_charset | identifier_name |
data_loader.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/. */
use crate::fetch;
use headers_core::HeaderMapExt;
use headers_ext::ContentType;
use hyper_serde::Serde;
use mime:... |
#[test]
fn base64_ct() {
assert_parse(
"data:application/octet-stream;base64,C62+7w==",
Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)),
None,
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
}
#[test]
fn base64_charset() {
assert_parse(
"data:text/plain;charset=koi8-r;... | {
assert_parse(
"data:;base64,C62+7w==",
Some(ContentType::from(
"text/plain; charset=US-ASCII".parse::<Mime>().unwrap(),
)),
Some("us-ascii"),
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
} | identifier_body |
data_loader.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/. */
use crate::fetch;
use headers_core::HeaderMapExt;
use headers_ext::ContentType;
use hyper_serde::Serde;
use mime:... | Some("us-ascii"),
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
}
#[test]
fn base64_ct() {
assert_parse(
"data:application/octet-stream;base64,C62+7w==",
Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)),
None,
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
}
#[test]
fn ba... | Some(ContentType::from(
"text/plain; charset=US-ASCII".parse::<Mime>().unwrap(),
)), | random_line_split |
public_api.js | /**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc | */
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export { AnimationDriver, ... | random_line_split | |
dom_adapter.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank } from '../facade/lang';
var _DOM = null;
export function getDOM() {
return _DOM;
}
export funct... |
;
}
//# sourceMappingURL=dom_adapter.js.map | { this._attrToPropMap = value; } | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.