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
logger.rs
extern crate log4rs; extern crate log; extern crate libc; use std::error::Error; use indy; pub struct IndyCliLogger; impl IndyCliLogger { pub fn init(path: &str) -> Result<(), String> { log4rs::init_file(path, Default::default()) .map_err(|err| format!("Cannot init Indy CLI logger: {}", err....
} #[macro_export] macro_rules! try_log { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { error!("try_log! | {}", err); return Err(From::from(err)) } }) } macro_rules! _log_err { ($lvl:expr, $expr:expr) => ( |err| { log!($lvl,...
indy::logger::set_logger(log::logger()) .map_err(|_| "Cannot init Libindy logger".to_string()) }
random_line_split
logger.rs
extern crate log4rs; extern crate log; extern crate libc; use std::error::Error; use indy; pub struct IndyCliLogger; impl IndyCliLogger { pub fn init(path: &str) -> Result<(), String>
} #[macro_export] macro_rules! try_log { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { error!("try_log! | {}", err); return Err(From::from(err)) } }) } macro_rules! _log_err { ($lvl:expr, $expr:expr) => ( |err| { log!($lvl...
{ log4rs::init_file(path, Default::default()) .map_err(|err| format!("Cannot init Indy CLI logger: {}", err.description()))?; indy::logger::set_logger(log::logger()) .map_err(|_| "Cannot init Libindy logger".to_string()) }
identifier_body
contrast.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ip.rsh" #pragma rs_fp_relaxed static float brightM = 0.f; static float brightC = 0.f; void setBright(float v) { bright...
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_...
(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_down(&sym, DELAY); } } pub fn release_key(key: Key) { if let Ok(xdo) = XDo::new(None) { let sym = get_keysym(key); let _ = xdo.send_keysequence_up(&sym, DELAY); } } pu...
press_key
identifier_name
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_...
send_str(&c.to_string()); } /// Send a string as keyboard events. Unsupported chars are silently ignored. pub fn send_str(msg: &str) { if let Ok(xdo) = XDo::new(None) { let _ = xdo.enter_text(msg, DELAY); } }
} } /// Send a unicode character. Unsupported chars are silently ignored. pub fn send_char(c: char) {
random_line_split
linux.rs
extern crate libxdo; extern crate itertools; use std::borrow::Cow; use self::itertools::Itertools; use self::libxdo::XDo; use super::{Physical, Key}; const DELAY: u32 = 12_000; // microseconds // Keysyms can be found via the xev tool or here: // https://cgit.freedesktop.org/xorg/proto/x11proto/tree/ fn get_physical_...
{ if let Ok(xdo) = XDo::new(None) { let _ = xdo.enter_text(msg, DELAY); } }
identifier_body
remake_model_files.py
import os from pathlib import Path import shutil import joblib import hvc from config import rewrite_config HERE = Path(__file__).parent DATA_FOR_TESTS = HERE / ".." / "data_for_tests" TEST_CONFIGS = DATA_FOR_TESTS.joinpath("config.yml").resolve() FEATURE_FILES_DST = DATA_FOR_TESTS.joinpath("feature_files").resolv...
"output_dir": ("replace with tmp_output_dir", str(MODEL_FILES_DST)), } select_config_rewritten = rewrite_config( select_config, str(MODEL_FILES_DST), replace_dict ) select_output_before = [ select_output_dir for select_output_dir in sorted...
for model_name, ( select_config, feature_filename, ) in config_feature_file_pairs.items(): print("running {} to create model files".format(select_config)) # have to put tmp_output_dir into yaml file select_config = TEST_CONFIGS / select_config feature_file = sorted(FE...
identifier_body
remake_model_files.py
import os from pathlib import Path import shutil import joblib import hvc from config import rewrite_config HERE = Path(__file__).parent DATA_FOR_TESTS = HERE / ".." / "data_for_tests" TEST_CONFIGS = DATA_FOR_TESTS.joinpath("config.yml").resolve() FEATURE_FILES_DST = DATA_FOR_TESTS.joinpath("feature_files").resolv...
if len(select_output_dir) != 1: raise ValueError( "incorrect number of outputs when looking for select " "ouput dirs:\n{}".format(select_output_dir) ) else: select_output_dir = select_output_dir[0] # arbitrarily grab the last ....
after for after in select_output_after if after not in select_output_before ]
random_line_split
remake_model_files.py
import os from pathlib import Path import shutil import joblib import hvc from config import rewrite_config HERE = Path(__file__).parent DATA_FOR_TESTS = HERE / ".." / "data_for_tests" TEST_CONFIGS = DATA_FOR_TESTS.joinpath("config.yml").resolve() FEATURE_FILES_DST = DATA_FOR_TESTS.joinpath("feature_files").resolv...
(): for model_name, ( select_config, feature_filename, ) in config_feature_file_pairs.items(): print("running {} to create model files".format(select_config)) # have to put tmp_output_dir into yaml file select_config = TEST_CONFIGS / select_config feature_file = s...
main
identifier_name
remake_model_files.py
import os from pathlib import Path import shutil import joblib import hvc from config import rewrite_config HERE = Path(__file__).parent DATA_FOR_TESTS = HERE / ".." / "data_for_tests" TEST_CONFIGS = DATA_FOR_TESTS.joinpath("config.yml").resolve() FEATURE_FILES_DST = DATA_FOR_TESTS.joinpath("feature_files").resolv...
select_config, str(MODEL_FILES_DST), replace_dict ) select_output_before = [ select_output_dir for select_output_dir in sorted(MODEL_FILES_DST.glob("*select*output*")) if select_output_dir.is_dir() ] hvc.select(select_config_rewritten) ...
print("running {} to create model files".format(select_config)) # have to put tmp_output_dir into yaml file select_config = TEST_CONFIGS / select_config feature_file = sorted(FEATURE_FILES_DST.glob(feature_filename)) if len(feature_file) != 1: raise ValueError( ...
conditional_block
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_e...
fn track_drop(&mut self, _old_low_bits: u64, _old_high_bits: u64, _new_low_bits: u64, _new_high_bits: u64) {} } #[cfg(test)] mod tests { use super::RensaCoefTracker; use rensa_tracker::RensaTracker; #[test] fn test_score() { let mut tracker = RensaCoefTracker::new(); tracker.track...
{}
identifier_body
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_e...
assert_eq!(4, tracker.num_erased[1]); assert_eq!(4, tracker.num_erased[2]); assert_eq!(4, tracker.num_erased[3]); assert_eq!(4, tracker.num_erased[4]); assert_eq!(5, tracker.num_erased[5]); assert_eq!(1, tracker.coef(1)); assert_eq!(8, tracker.coef(2)); ...
let mut tracker = RensaCoefTracker::new(); let rensa_result = bf.simulate_with_tracker(&mut tracker); assert_eq!(5, rensa_result.chain);
random_line_split
rensa_coef_tracker.rs
use field_bit::FieldBit; use rensa_tracker::RensaTracker; use score; pub struct RensaCoefTracker { pub num_erased: [usize; 20], pub long_bonus_coef: [usize; 20], pub color_bonus_coef: [usize; 20], } impl RensaCoefTracker { pub fn new() -> RensaCoefTracker { RensaCoefTracker { num_e...
(&mut self, nth_chain: usize, num_erased: usize, long_bonus_coef: usize, color_bonus_coef: usize) { self.num_erased[nth_chain] = num_erased; self.long_bonus_coef[nth_chain] = long_bonus_coef; self.color_bonus_coef[nth_chain] = color_bonus_coef; } fn track_vanish(&mut self, _nth_chain: us...
track_coef
identifier_name
__init__.py
"""Support for Xiaomi Miio.""" from datetime import timedelta import logging from miio.gateway import GatewayException from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_TOKEN from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordina...
"""Set up the Xiaomi Miio device component from a config entry.""" model = entry.data[CONF_MODEL] # Identify platforms to setup if model in MODELS_SWITCH: platforms = SWITCH_PLATFORMS else: return False for component in platforms: hass.async_create_task( hass.co...
identifier_body
__init__.py
"""Support for Xiaomi Miio.""" from datetime import timedelta import logging from miio.gateway import GatewayException from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_TOKEN from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordina...
async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the Xiaomi Miio components from a config entry.""" hass.data.setdefault(DOMAIN, {}) if entry.data[CONF_FLOW_TYPE] == CONF_GATEWAY: if not await async_setup_gateway_entry(hass, entry): ...
async def async_setup(hass: core.HomeAssistant, config: dict): """Set up the Xiaomi Miio component.""" return True
random_line_split
__init__.py
"""Support for Xiaomi Miio.""" from datetime import timedelta import logging from miio.gateway import GatewayException from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_TOKEN from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordina...
( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the Xiaomi Gateway component from a config entry.""" host = entry.data[CONF_HOST] token = entry.data[CONF_TOKEN] name = entry.title gateway_id = entry.unique_id # For backwards compat if entry.unique_id.endswith(...
async_setup_gateway_entry
identifier_name
__init__.py
"""Support for Xiaomi Miio.""" from datetime import timedelta import logging from miio.gateway import GatewayException from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_TOKEN from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordina...
for component in platforms: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
return False
conditional_block
resources.ts
import Collection from './Collection'; import Me from './Me'; import Resource from './resource'; declare const me: Me; export default class Resources extends Collection<Resource> { comparator(res1: Resource, res2: Resource): number { const name1 = res1.mucDisplayName.toLowerCase(), name2 = res...
const pattern = new RegExp('^' + letters + '.*$', 'i'); const filtered = collection.filter(function(data) { const nick = data.mucDisplayName; if (nick === me.nick) return false; return pattern.test(nick); }); return new module.exports(filtered); ...
{ const resource = new Resource({id: this.parent.jid.bare + '/all'}); collection.add(resource); }
conditional_block
resources.ts
import Collection from './Collection'; import Me from './Me'; import Resource from './resource'; declare const me: Me; export default class Resources extends Collection<Resource> { comparator(res1: Resource, res2: Resource): number { const name1 = res1.mucDisplayName.toLowerCase(), name2 = res...
}); return new module.exports(filtered); } }
if (nick === me.nick) return false; return pattern.test(nick);
random_line_split
resources.ts
import Collection from './Collection'; import Me from './Me'; import Resource from './resource'; declare const me: Me; export default class Resources extends Collection<Resource> { comparator(res1: Resource, res2: Resource): number
search(letters: string, removeMe: boolean, addAll: boolean) { if (letters === '' && !removeMe) return this; const collection = this; if (addAll) { const resource = new Resource({id: this.parent.jid.bare + '/all'}); collection.add(resource); } const...
{ const name1 = res1.mucDisplayName.toLowerCase(), name2 = res2.mucDisplayName.toLowerCase(); return (name1 > name2) ? 1 : (name1 < name2) ? -1 : 0; }
identifier_body
resources.ts
import Collection from './Collection'; import Me from './Me'; import Resource from './resource'; declare const me: Me; export default class Resources extends Collection<Resource> { comparator(res1: Resource, res2: Resource): number { const name1 = res1.mucDisplayName.toLowerCase(), name2 = res...
(letters: string, removeMe: boolean, addAll: boolean) { if (letters === '' && !removeMe) return this; const collection = this; if (addAll) { const resource = new Resource({id: this.parent.jid.bare + '/all'}); collection.add(resource); } const pattern = n...
search
identifier_name
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn detect(bytes: &[u8]) -> BinaryType { if scan_elf(bytes)
else { BinaryType::UNKNOWN } } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L', 'F'] ident[0..4] == [0x7F, 0x45, 0x4C, 0x46] } // fn scan_coff // fn...
{ BinaryType::ELF }
conditional_block
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn
(bytes: &[u8]) -> BinaryType { if scan_elf(bytes) { BinaryType::ELF } else { BinaryType::UNKNOWN } } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L...
detect
identifier_name
mod.rs
#[derive(PartialEq, Debug)] pub enum BinaryType { ELF, COFF, PE, DOS, UNKNOWN, } pub fn detect(bytes: &[u8]) -> BinaryType { if scan_elf(bytes) { BinaryType::ELF } else {
} } // TODO: Can the other 12 bytes be utilized for more confirmation? fn scan_elf(bytes: &[u8]) -> bool { let ident: &[u8] = &bytes[0..15]; // [0x7F, 0x45, 0x4C, 0x46] = [0x7F, 'E', 'L', 'F'] ident[0..4] == [0x7F, 0x45, 0x4C, 0x46] } // fn scan_coff // fn scan_pe
BinaryType::UNKNOWN
random_line_split
mm4parser.py
IZ # # R(e) 5.7724 73.4297 76.0735 # R(z) 5.7221(-0.0518) 74.0311(-0.0285) 76.7102(-0.0064) # # (2) UNIT = AU A**2 # # IX IY IZ # # R(e) 34.7661 442.2527 458.1757 #...
random_line_split
mm4parser.py
(self, *args, **kwargs): # Call the __init__ method of the superclass super(MM4, self).__init__(logname="MM4", *args, **kwargs) def __str__(self): """Return a string representation of the object.""" return "MM4 log file %s" % (self.filename) def __repr__(self)...
__init__
identifier_name
mm4parser.py
def extract(self, inputfile, line): """Extract information from the file object inputfile.""" # Number of atoms. # Example: THE COORDINATES OF 20 ATOMS ARE READ IN. if line[0:28] == ' THE COORDINATES OF': self.updateprogress(input...
"""Return a representation of the object.""" return 'MM4("%s")' % (self.filename)
identifier_body
mm4parser.py
else: self.natom = natom # Extract the atomic numbers and coordinates from the optimized (final) geometry # Example: # FINAL ATOMIC COORDINATE # ATOM X Y Z TYPE # C( 1) -3.21470 -0....
assert self.natom == natom
conditional_block
prism-line-highlight.js
(function(){ if(!window.Prism) { return; } function
(expr, con) { return Array.prototype.slice.call((con || document).querySelectorAll(expr)); } var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-line-offset') || 0; var lineHeight = parseFloat(getCom...
$$
identifier_name
prism-line-highlight.js
(function(){ if(!window.Prism) { return; } function $$(expr, con) { return Array.prototype.slice.call((con || document).querySelectorAll(expr)); } var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-...
addEventListener('hashchange', applyHash); })();
random_line_split
prism-line-highlight.js
(function(){ if(!window.Prism) { return; } function $$(expr, con) { return Array.prototype.slice.call((con || document).querySelectorAll(expr)); } var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-...
var id = hash.slice(0, hash.lastIndexOf('.')), pre = document.getElementById(id); if (!pre) { return; } if (!pre.hasAttribute('data-line')) { pre.setAttribute('data-line', ''); } highlightLines(pre, range, 'temporary '); document.querySelector('.temporary.line-highlight').scrollIntoView(); } var ...
{ return; }
conditional_block
prism-line-highlight.js
(function(){ if(!window.Prism) { return; } function $$(expr, con)
var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-line-offset') || 0; var lineHeight = parseFloat(getComputedStyle(pre).lineHeight); for (var i=0, range; range = ranges[i++];) { range = range.s...
{ return Array.prototype.slice.call((con || document).querySelectorAll(expr)); }
identifier_body
via_app_data.py
"""Bootstrap""" from __future__ import absolute_import, unicode_literals import logging import sys import traceback from contextlib import contextmanager from subprocess import CalledProcessError from threading import Lock, Thread from virtualenv.info import fs_supports_symlink from virtualenv.seed.embed.base_embed i...
(cls, parser, interpreter, app_data): super(FromAppData, cls).add_parser_arguments(parser, interpreter, app_data) can_symlink = app_data.transient is False and fs_supports_symlink() parser.add_argument( "--symlink-app-data", dest="symlink_app_data", action="st...
add_parser_arguments
identifier_name
via_app_data.py
"""Bootstrap""" from __future__ import absolute_import, unicode_literals import logging import sys import traceback from contextlib import contextmanager from subprocess import CalledProcessError from threading import Lock, Thread from virtualenv.info import fs_supports_symlink from virtualenv.seed.embed.base_embed i...
self.symlinks = options.symlink_app_data @classmethod def add_parser_arguments(cls, parser, interpreter, app_data): super(FromAppData, cls).add_parser_arguments(parser, interpreter, app_data) can_symlink = app_data.transient is False and fs_supports_symlink() parser.add_argument...
super(FromAppData, self).__init__(options)
random_line_split
via_app_data.py
"""Bootstrap""" from __future__ import absolute_import, unicode_literals import logging import sys import traceback from contextlib import contextmanager from subprocess import CalledProcessError from threading import Lock, Thread from virtualenv.info import fs_supports_symlink from virtualenv.seed.embed.base_embed i...
base = super(FromAppData, self).__unicode__() msg = ", via={}, app_data_dir={}".format("symlink" if self.symlinks else "copy", self.app_data) return base[:-1] + msg + base[-1]
identifier_body
via_app_data.py
"""Bootstrap""" from __future__ import absolute_import, unicode_literals import logging import sys import traceback from contextlib import contextmanager from subprocess import CalledProcessError from threading import Lock, Thread from virtualenv.info import fs_supports_symlink from virtualenv.seed.embed.base_embed i...
if fail: raise RuntimeError("seed failed due to failing to download wheels {}".format(", ".join(fail.keys()))) yield name_to_whl def installer_class(self, pip_version_tuple): if self.symlinks and pip_version_tuple: # symlink support requires pip 19.3+ if...
thread.join()
conditional_block
Input.js
/** * @file * @copyright 2020 Aleksej Komarov * @license MIT */ import { classes, isFalsy } from 'common/react'; import { Component, createRef } from 'inferno'; import { Box } from './Box'; const toInputValue = value => { if (isFalsy(value)) { return ''; } return value; }; export class Input extends Co...
if (onInput) { onInput(e, e.target.value); } }; this.handleFocus = e => { const { editing } = this.state; if (!editing) { this.setEditing(true); } }; this.handleBlur = e => { const { editing } = this.state; const { onChange } = this.props; ...
}
random_line_split
Input.js
/** * @file * @copyright 2020 Aleksej Komarov * @license MIT */ import { classes, isFalsy } from 'common/react'; import { Component, createRef } from 'inferno'; import { Box } from './Box'; const toInputValue = value => { if (isFalsy(value)) { return ''; } return value; }; export class Input extends Co...
(prevProps, prevState) { const { editing } = this.state; const prevValue = prevProps.value; const nextValue = this.props.value; const input = this.inputRef.current; if (input && !editing && prevValue !== nextValue) { input.value = toInputValue(nextValue); } } setEditing(editing) { ...
componentDidUpdate
identifier_name
Input.js
/** * @file * @copyright 2020 Aleksej Komarov * @license MIT */ import { classes, isFalsy } from 'common/react'; import { Component, createRef } from 'inferno'; import { Box } from './Box'; const toInputValue = value => { if (isFalsy(value)) { return ''; } return value; }; export class Input extends Co...
if (onInput) { onInput(e, e.target.value); } }; this.handleFocus = e => { const { editing } = this.state; if (!editing) { this.setEditing(true); } }; this.handleBlur = e => { const { editing } = this.state; const { onChange } = this.props; ...
{ this.setEditing(true); }
conditional_block
max-path-sum.py
# -*- coding: utf-8 -*- from Node import Node res = float("-inf") # 只有顶层root节点才可能即经过左边 又经过右边 def maxPathSum(root): if not root: return 0 max
ot.left = Node(2) root.right = Node(10); root.left.left = Node(20); root.left.right = Node(1); root.right.right = Node(-25); root.right.right.left = Node(3); root.right.right.right = Node(4); maxPathSum(root) print res
_l = maxPathSum(root.left) max_r = maxPathSum(root.right) max_single = max(max(max_l, max_r) + root.data, root.data) max_top = max(max_single, max_l + max_r + root.data) global res res = max(res, max_top) return max_single # Driver program root = Node(10) ro
identifier_body
max-path-sum.py
# -*- coding: utf-8 -*- from Node import Node res = float("-inf") # 只有顶层root节点才可能即经过左边 又经过右边 def maxPathSum(root): if not root: return 0 max_l = maxPathSum(root.
max_r = maxPathSum(root.right) max_single = max(max(max_l, max_r) + root.data, root.data) max_top = max(max_single, max_l + max_r + root.data) global res res = max(res, max_top) return max_single # Driver program root = Node(10) root.left = Node(2) root.right = Node(10); root.left.left = Nod...
left)
conditional_block
max-path-sum.py
# -*- coding: utf-8 -*- from Node import Node res = float("-inf")
def maxPathSum(root): if not root: return 0 max_l = maxPathSum(root.left) max_r = maxPathSum(root.right) max_single = max(max(max_l, max_r) + root.data, root.data) max_top = max(max_single, max_l + max_r + root.data) global res res = max(res, max_top) return max_single # ...
# 只有顶层root节点才可能即经过左边 又经过右边
random_line_split
max-path-sum.py
# -*- coding: utf-8 -*- from Node import Node res = float("-inf") # 只有顶层root节点才可能即经过左边 又经过右边 def maxPathSum(root): if not root:
n 0 max_l = maxPathSum(root.left) max_r = maxPathSum(root.right) max_single = max(max(max_l, max_r) + root.data, root.data) max_top = max(max_single, max_l + max_r + root.data) global res res = max(res, max_top) return max_single # Driver program root = Node(10) root.left = Node(2) ro...
retur
identifier_name
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64; use core::num::Float; use core::f64; // pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; ...
() { let x: f64 = f64::infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, f64::infinity()); } #[test] fn expf64_test3() { let x: f64 = f64::neg_infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 0.0); } #[test] fn expf64_test4() { let x: f64 =...
expf64_test2
identifier_name
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64; use core::num::Float; use core::f64; // pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; ...
#[test] fn expf64_test4() { let x: f64 = 10.0; let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 1024.0); } }
{ let x: f64 = f64::neg_infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, 0.0); }
identifier_body
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64;
// pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result.is_nan(), true); } #[test] fn expf64_test2() { let x: f64 = f64::infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, f64...
use core::num::Float; use core::f64;
random_line_split
lib.rs
#![deny(unsafe_code)] extern crate app_units; extern crate atomic_refcell; #[macro_use] extern crate bitflags; extern crate canvas_traits; extern crate euclid; extern crate fnv; extern crate fxhash; extern crate gfx; extern crate gfx_traits; #[macro_use] extern crate html5ever; extern crate ipc_channel; extern crate ...
/* 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/. */
random_line_split
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c; const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)] #[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-...
(&self, threshold: u8, filter_time: u8) -> &Self { let sens = 9 * 2 + 17 - 2 * threshold; self // sleep mode .set_register(Register::CTRL_REG1, 0); // set accumulation threshold self.set_register(Register::FF_MT_THS, (sens & 0x7F)); // set debounce threshold ...
set_sensitivity
identifier_name
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c; const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)] #[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-...
} #[derive(Clone, Copy)] pub struct Accel { /// X component pub x: i16, /// Y component pub y: i16, /// Z component pub z: i16, } pub struct MMA8652FC<'a>(pub &'a I2C1); impl<'a> MMA8652FC<'a> { pub fn init(&self) { self // Normal Mode .set_register(Register::...
{ *self as u8 }
identifier_body
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c;
#[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-axis sample (R) OUT_X_MSB = 0x01, /// [7:2] are 6 LSBs of the 14-bit X-axis sample (R) OUT_X_LSB = 0x02, /// [7:0] are 8 MSBs of the 14-bit Y-axis sample (R) OUT_Y_MSB ...
const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)]
random_line_split
basic_shape.rs
-box define_css_keyword_enum!(ShapeBox: "margin-box" => MarginBox, "border-box" => BorderBox, "padding-box" => PaddingBox, "content-box" => ContentBox ); add_impls_for_keyword_enum!(ShapeBox); /// A shape source, for some reference box. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSi...
#[inline]
random_line_split
basic_shape.rs
use std::fmt; use style_traits::{HasViewportPercentage, ToCss}; use values::computed::ComputedValueAsSpecified; use values::generics::BorderRadiusSize; use values::generics::position::Position; use values::generics::rect::Rect; use values::specified::url::SpecifiedUrl; /// A clipping shape, for `clip-path`. pub type C...
() -> Self { ShapeRadius::ClosestSide } } impl<L: ToCss> ToCss for ShapeRadius<L> {
default
identifier_name
test_climatology.py
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised ...
tests.main()
conditional_block
test_climatology.py
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised ...
cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self....
iris.save(self.cube_ref, self.path_temp_nc)
random_line_split
test_climatology.py
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised ...
@classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with op...
cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube
identifier_body
test_climatology.py
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised ...
(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, ...
test_file_to_file
identifier_name
ListCard.component.js
import React from 'react'; import TruncateMarkup from 'react-truncate-markup'; import ProfileImage from '../../general/ProfileImage.component'; import SkeletonText from '../../base/Skeleton/Text'; import SkeletonUser from '../../base/Skeleton/User'; import Link from '../../general/Link.component'; import toColor from '...
return ( <div className={'list-card mr-4 align-top ' + className} style={style} data-cy={`list-card-${list.title}`} > <Link href={`/lister/${list._id}`} onClick={onClick}> <div className="list-card-wrap"> <div className="list-card-cover"> ...
{ return ( <div className={'ListCard__skeleton p-0 mr-4 ' + className} ref={cardRef} > <div className="ListCard__skeleton__cover" /> <div className="p-3"> <SkeletonText lines={3} color="#e9eaeb" /> <SkeletonUser name={tr...
conditional_block
ListCard.component.js
import React from 'react'; import TruncateMarkup from 'react-truncate-markup'; import ProfileImage from '../../general/ProfileImage.component'; import SkeletonText from '../../base/Skeleton/Text'; import SkeletonUser from '../../base/Skeleton/User'; import Link from '../../general/Link.component'; import toColor from '...
extends React.Component { hasOwner = () => { const list = this.props.list; return !!(list && list.owner && list.owner.name); }; renderBookCover(id, img) { const POSITIONS = [ 'align-self-start', 'align-self-center', 'align-self-end' ]; const SIZES = [ 'list-card-brick...
ListCard
identifier_name
ListCard.component.js
import React from 'react'; import TruncateMarkup from 'react-truncate-markup'; import ProfileImage from '../../general/ProfileImage.component'; import SkeletonText from '../../base/Skeleton/Text'; import SkeletonUser from '../../base/Skeleton/User'; import Link from '../../general/Link.component'; import toColor from '...
export default ListCard;
random_line_split
Script.d.ts
/// <reference path="ISignal.d.ts" /> declare module hifi { interface ITimer { } interface ISharedNodePointer { } /** * /libraries/script-engine/src/ScriptEngine.h * September 16th, 2014 */ interface IScript { setIsAvatar(isAvatar: boolean): void; stop(): void; ...
setInterval(func: Function, intervalMS: number): ITimer; setTimeout(func: Function, timeoutMS: number): ITimer; clearInterval(timer: ITimer): void; clearTimeout(timer: ITimer): void; include(includeFile: string): void; load(loadFile: string): void; print(message:...
*/ evaluate(program: string, fileName?: string, lineNumber?: number): any;
random_line_split
base_graph.py
import tensorflow as tf class BaseGraph: """ A generic computation graph class, with only two constraints are 1. The requirements for net instance passed in: - net should have method of define_net - net should have method of get_placeholders 2. Losses can only be calculated w...
(self): self.logger.info('[Graph] Constructing graph now...') self.graph = tf.Graph() with self.graph.as_default(): self.predictions = self.net.define_net() self.x_pl, self.y_pl, self.is_training_pl = self.net.get_placeholders() # Loss try: ...
_define_graph
identifier_name
base_graph.py
import tensorflow as tf class BaseGraph: """ A generic computation graph class, with only two constraints are 1. The requirements for net instance passed in: - net should have method of define_net - net should have method of get_placeholders 2. Losses can only be calculated w...
tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.y_pl, logits=self.predictions)) except ValueError as e: self.logger.warn(e) self.loss = self.losses[self.loss_type] tf.summary.scalar("loss", self.loss) tf.summary.scalar("lr",...
self.losses['mse'] = tf.reduce_mean(tf.square(self.predictions - self.y_pl)) self.losses['cross_entropy'] = tf.reduce_mean(
random_line_split
base_graph.py
import tensorflow as tf class BaseGraph: """ A generic computation graph class, with only two constraints are 1. The requirements for net instance passed in: - net should have method of define_net - net should have method of get_placeholders 2. Losses can only be calculated w...
def get_optimizer(self): return self.optimizer
return self.graph, self.init_graph
identifier_body
feed_mapping_status.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
(proto.Enum): r"""Possible statuses of a feed mapping.""" UNSPECIFIED = 0 UNKNOWN = 1 ENABLED = 2 REMOVED = 3 __all__ = tuple(sorted(__protobuf__.manifest))
FeedMappingStatus
identifier_name
feed_mapping_status.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package=...
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
random_line_split
feed_mapping_status.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
__all__ = tuple(sorted(__protobuf__.manifest))
r"""Possible statuses of a feed mapping.""" UNSPECIFIED = 0 UNKNOWN = 1 ENABLED = 2 REMOVED = 3
identifier_body
access.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 ...
<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T { unsafe { &mut *self.unsafe_get() } } pub fn close(&self, _missile: &HomingMissile) { // This unsafety is OK because with a homing missile we're guaranteed to // be the only task looking at the `closed` flag (and are therefore ...
get_mut
identifier_name
access.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 ...
} } pub fn grant<'a>(&'a mut self, token: uint, missile: HomingMissile) -> Guard<'a, T> { // This unsafety is actually OK because the homing missile argument // guarantees that we're on the same event loop as all the other objects // attempting to get access...
queue: vec![], held: false, closed: false, data: data, }))
random_line_split
access.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 ...
} #[unsafe_destructor] impl<'a, T> Drop for Guard<'a, T> { fn drop(&mut self) { // This guard's homing missile is still armed, so we're guaranteed to be // on the same I/O event loop, so this unsafety should be ok. assert!(self.missile.is_some()); let inner: &mut Inner<T> = unsafe ...
{ unsafe { &mut (*self.access.inner.get()).data } }
identifier_body
binaryEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
/** * The resource of the binary resource. */ getResource(): URI { return this.resource; } /** * The size of the binary resource if known. */ getSize(): number { return this.size; } /** * The mime of the binary resource if known. */ getMime(): string { return this.mime; } /** * The et...
{ return this.name; }
identifier_body
binaryEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.mime = metadata.get(DataUri.META_DATA_MIME); } } /** * The name of the binary resource. */ getName(): string { return this.name; } /** * The resource of the binary resource. */ getResource(): URI { return this.resource; } /** * The size of the binary resource if known. */ getSize...
{ this.size = Number(metadata.get(DataUri.META_DATA_SIZE)); }
conditional_block
binaryEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
( resource: URI, name: string, @IFileService private fileService: IFileService ) { super(); this.resource = resource; this.name = name; if (resource.scheme === Schemas.data) { const metadata = DataUri.parseMetaData(resource); if (metadata.has(DataUri.META_DATA_SIZE)) { this.size = Number(meta...
constructor
identifier_name
binaryEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.size = stat.size; return this; }); } return TPromise.wrap(this); } }
if (this.fileService.canHandleResource(this.resource)) { return this.fileService.resolveFile(this.resource).then(stat => { this.etag = stat.etag;
random_line_split
[search].ts
import type { NextApiHandler } from 'next' import jwt from 'next-auth/jwt' import { isMember } from '../../../../src/auth/check-user' import { apiError } from '../../../../src/services/error-response' import MapModel from '../../../../src/models/map' const signingKey = process.env.JWT_SIGNING_PRIVATE_KEY const handle...
}) } catch (err) { apiError(res, 500)(err) } } export default handler
try { const result = await MapModel.getSearchResults(req.query.q as string) return res.status(200).json({ maps: result
random_line_split
[search].ts
import type { NextApiHandler } from 'next' import jwt from 'next-auth/jwt' import { isMember } from '../../../../src/auth/check-user' import { apiError } from '../../../../src/services/error-response' import MapModel from '../../../../src/models/map' const signingKey = process.env.JWT_SIGNING_PRIVATE_KEY const handle...
try { const result = await MapModel.getSearchResults(req.query.q as string) return res.status(200).json({ maps: result }) } catch (err) { apiError(res, 500)(err) } } export default handler
{ res.status(400).send('Bad Request: Expected query param. Ex. q=abc') return }
conditional_block
ProductVariantDeleteDialog.tsx
import Button from "@material-ui/core/Button"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-...
const ProductVariantDeleteDialog = withStyles(styles, { name: "ProductVariantDeleteDialog" })( ({ classes, confirmButtonState, name, open, onConfirm, onClose }: ProductVariantDeleteDialogProps) => ( <Dialog open={open}> <DialogTitle> {i18n.t("Delete variant", { context: "...
}
random_line_split
resourcedetail.js
// Copyright 2015 Google Inc. 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...
(baseUrl) { return `${baseUrl}/:objectNamespace/:objectName`; }
appendDetailParamsToUrl
identifier_name
resourcedetail.js
// Copyright 2015 Google Inc. 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...
super(objectName); /** @export {string} Namespace of this object. */ this.objectNamespace = objectNamespace; } } export function appendDetailParamsToUrl(baseUrl) { return `${baseUrl}/:objectNamespace/:objectName`; }
* @param {string} objectNamespace * @param {string} objectName */ constructor(objectNamespace, objectName) {
random_line_split
resourcedetail.js
// Copyright 2015 Google Inc. 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...
} export function appendDetailParamsToUrl(baseUrl) { return `${baseUrl}/:objectNamespace/:objectName`; }
{ super(objectName); /** @export {string} Namespace of this object. */ this.objectNamespace = objectNamespace; }
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import sys from setuptools import setup from setuptools import find_packages with io.open('README.md', 'rt', encoding='utf8') as f: README = f.read() if sys.argv[-1] == 'test':
if sys.argv[-1] == 'publish': os.system('python setup.py sdist') os.system('twine upload dist/*') sys.exit(0) VERSION = '0.0.7' REQUIRES = ['google-api-python-client>=1.5.3', 'pandas>=0.22.0', 'fire>=0.1.3'] GITHUB_URL = 'https://github.com/condad/google-objects' setup( name='google_objects', pa...
os.system('python -sm unittest discover tests "*_test.py"') sys.exit(0)
conditional_block
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import sys from setuptools import setup from setuptools import find_packages with io.open('README.md', 'rt', encoding='utf8') as f: README = f.read() if sys.argv[-1] == 'test': os.system('python -sm unittest discover tests "*_test.py"') ...
'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ], entry_points={ 'console_scripts': [ 'sheets-cli = google_objects.cli:main', ], }, )
random_line_split
colormaps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # __init__.py """ Convert colormaps to amira format Copyright (c) 2018, David Hoffman """ import os import matplotlib.cm import colorcet header = """# AmiraMesh 3D ASCII 2.0 define Lattice {N:d} Parameters {{ ContentType "Colormap" MinMax 0 {N:d}{extra:} }} L...
filename = os.path.splitext(filename)[0] + ".am" with open(filename, "w") as fp: fp.write(header.format(N=cmap.N, extra=extra)) # convert numbers to strings str_cmap = ([str(c) for c in cmap(i / (cmap.N - 1))] for i in range(cmap.N)) str_cmap = [" ".join(color) for color in str_...
cmap = matplotlib.cm.get_cmap(cmap)
conditional_block
colormaps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # __init__.py """ Convert colormaps to amira format Copyright (c) 2018, David Hoffman """ import os import matplotlib.cm import colorcet header = """# AmiraMesh 3D ASCII 2.0 define Lattice {N:d} Parameters {{ ContentType "Colormap" MinMax 0 {N:d}{extra:} }} L...
if __name__ == "__main__": qualitative = { "Pastel1", "Pastel2", "Paired", "Accent", "Dark2", "Set1", "Set2", "Set3", "tab10", "tab20", "tab20b", "tab20c", } for cmap_name, cmap in matplotlib.cm.cmap_d.items(...
if isinstance(cmap, str): cmap = matplotlib.cm.get_cmap(cmap) filename = os.path.splitext(filename)[0] + ".am" with open(filename, "w") as fp: fp.write(header.format(N=cmap.N, extra=extra)) # convert numbers to strings str_cmap = ([str(c) for c in cmap(i / (cmap.N - 1))] for i in...
identifier_body
colormaps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # __init__.py """ Convert colormaps to amira format Copyright (c) 2018, David Hoffman """ import os import matplotlib.cm import colorcet header = """# AmiraMesh 3D ASCII 2.0 define Lattice {N:d} Parameters {{
Lattice {{ float[4] Data }} @1 # Data section follows @1 """ qualitative_str = """ Interpolate 0 OutOfBoundsBehavior "CycleRight" LabelField 1 """ # for Label Field # Parameters { # MinMax 1 8, # ContentType "Colormap", # Interpolate 0 # OutOfBoundsBehavior "CycleRight" # LabelField 1...
ContentType "Colormap" MinMax 0 {N:d}{extra:} }}
random_line_split
colormaps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # __init__.py """ Convert colormaps to amira format Copyright (c) 2018, David Hoffman """ import os import matplotlib.cm import colorcet header = """# AmiraMesh 3D ASCII 2.0 define Lattice {N:d} Parameters {{ ContentType "Colormap" MinMax 0 {N:d}{extra:} }} L...
(cmap, filename, extra=""): if isinstance(cmap, str): cmap = matplotlib.cm.get_cmap(cmap) filename = os.path.splitext(filename)[0] + ".am" with open(filename, "w") as fp: fp.write(header.format(N=cmap.N, extra=extra)) # convert numbers to strings str_cmap = ([str(c) for c in ...
cm_to_amira
identifier_name
encodedword.py
# coding:utf-8 import logging import regex as re import email.quoprimime import email.base64mime from base64 import b64encode from flanker.mime.message import charsets, errors log = logging.getLogger(__name__) #deal with unfolding foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)") def unfold(value): """ ...
def mime_to_unicode(header): """ Takes a header value and returns a fully decoded unicode string. It differs from standard Python's mail.header.decode_header() because: - it is higher level, i.e. returns a unicode string instead of an array of tuples - it accepts Unicode and non...
return mime_to_unicode(header)
identifier_body
encodedword.py
# coding:utf-8 import logging import regex as re import email.quoprimime import email.base64mime from base64 import b64encode from flanker.mime.message import charsets, errors log = logging.getLogger(__name__) #deal with unfolding foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)") def unfold(value): """ ...
)''', re.VERBOSE | re.IGNORECASE | re.MULTILINE) def decode_part(charset, encoding, value): """ Attempts to decode part, understands 'q' - quoted encoding 'b' - base64 mime encoding Returns (charset, decoded-string) """ if encoding == 'q': return (charset, email.quoprimime.header_...
(?P<encoded>.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?=
random_line_split
encodedword.py
# coding:utf-8 import logging import regex as re import email.quoprimime import email.base64mime from base64 import b64encode from flanker.mime.message import charsets, errors log = logging.getLogger(__name__) #deal with unfolding foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)") def unfold(value): """ ...
return (charset, email.base64mime.decode(value)) elif not encoding: return (charset, value) else: raise errors.DecodingError( "Unknown encoding: {0}".format(encoding))
= '==='[:4 - paderr]
conditional_block
encodedword.py
# coding:utf-8 import logging import regex as re import email.quoprimime import email.base64mime from base64 import b64encode from flanker.mime.message import charsets, errors log = logging.getLogger(__name__) #deal with unfolding foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)") def unfold(value): """ ...
(header): """ Takes a header value and returns a fully decoded unicode string. It differs from standard Python's mail.header.decode_header() because: - it is higher level, i.e. returns a unicode string instead of an array of tuples - it accepts Unicode and non-ASCII strings as well...
mime_to_unicode
identifier_name
describemetriccollectiontypes.py
# Copyright 2013 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
(self, result): for metric in result.get('Metrics', []): print self.tabify(('METRIC-COLLECTION-TYPE', metric.get('Metric'))) for granularity in result.get('Granularities', []): print self.tabify(('METRIC-GRANULARITY-TYPE', granularity.get('Granulari...
print_result
identifier_name
describemetriccollectiontypes.py
# Copyright 2013 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
from requestbuilder.mixins import TabifyingMixin class DescribeMetricCollectionTypes(AutoScalingRequest, TabifyingMixin): DESCRIPTION = 'Describe auto-scaling metrics and granularities' LIST_TAGS = ['Metrics', 'Granularities'] def print_result(self, result): for metric in result.get('Metrics', []...
from euca2ools.commands.autoscaling import AutoScalingRequest
random_line_split
describemetriccollectiontypes.py
# Copyright 2013 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
DESCRIPTION = 'Describe auto-scaling metrics and granularities' LIST_TAGS = ['Metrics', 'Granularities'] def print_result(self, result): for metric in result.get('Metrics', []): print self.tabify(('METRIC-COLLECTION-TYPE', metric.get('Metric'))) for granularity in result.get('Granul...
identifier_body
describemetriccollectiontypes.py
# Copyright 2013 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
print self.tabify(('METRIC-GRANULARITY-TYPE', granularity.get('Granularity')))
conditional_block
test_discretization.py
from unittest import TestCase from tcontrol.discretization import c2d from ..transferfunction import tf from ..model_conversion import * from ..statespace import StateSpace import numpy as np from .tools.test_utility import assert_ss_equal class TestDiscretization(TestCase): def setUp(self): self.s1 = tf...
def test_c2d_matched(self): d_sys = c2d(self.s1, 1, 'matched') error = np.abs(d_sys.num - np.array([0.2298, 0.4597, 0.2298])) self.assertLessEqual(np.max(error), 1e-4)
error = np.abs(d_sys.num - np.array([0.2, 0.4, 0.2])) self.assertLessEqual(np.max(error), 1e-4)
random_line_split
test_discretization.py
from unittest import TestCase from tcontrol.discretization import c2d from ..transferfunction import tf from ..model_conversion import * from ..statespace import StateSpace import numpy as np from .tools.test_utility import assert_ss_equal class TestDiscretization(TestCase): def setUp(self): self.s1 = tf...
(self): a = c2d(self.ss, 1, 'foh') b = StateSpace([[0.540302, 0.841471], [-0.841471, 0.540302]], [[0.773644], [0.49675]], [[1, 0]], [[0.158529]], dt=1) assert_ss_equal(a, b) def test_c2d_tustin(self): d_sys = c2d(self.s1, 1, 'tustin') ...
test_c2d_foh
identifier_name
test_discretization.py
from unittest import TestCase from tcontrol.discretization import c2d from ..transferfunction import tf from ..model_conversion import * from ..statespace import StateSpace import numpy as np from .tools.test_utility import assert_ss_equal class TestDiscretization(TestCase): def setUp(self): self.s1 = tf...
def test_c2d_tustin(self): d_sys = c2d(self.s1, 1, 'tustin') error = np.abs(d_sys.num - np.array([0.2, 0.4, 0.2])) self.assertLessEqual(np.max(error), 1e-4) def test_c2d_matched(self): d_sys = c2d(self.s1, 1, 'matched') error = np.abs(d_sys.num - np.array([0.2298, 0.45...
a = c2d(self.ss, 1, 'foh') b = StateSpace([[0.540302, 0.841471], [-0.841471, 0.540302]], [[0.773644], [0.49675]], [[1, 0]], [[0.158529]], dt=1) assert_ss_equal(a, b)
identifier_body
test_state.py
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM from runtests.mpi import MPITest from nbodykit.cosmology import Planck15 as cosmo import numpy BoxSize = 100. Q = numpy.zeros((100, 3)) @MPITest([1, 4]) def
(comm): matter = Matter(cosmo, BoxSize, Q, comm) cdm = CDM(cosmo, BoxSize, Q, comm) cdm.a['S'] = 1.0 cdm.a['P'] = 1.0 baryon = Baryon(cosmo, BoxSize, Q, comm) baryon.a['S'] = 1.0 baryon.a['P'] = 1.0 state = StateVector(cosmo, {'0': baryon, '1' : cdm}, comm) state.a['S'] = 1.0 ...
test_create
identifier_name
test_state.py
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM from runtests.mpi import MPITest from nbodykit.cosmology import Planck15 as cosmo import numpy BoxSize = 100. Q = numpy.zeros((100, 3))
cdm = CDM(cosmo, BoxSize, Q, comm) cdm.a['S'] = 1.0 cdm.a['P'] = 1.0 baryon = Baryon(cosmo, BoxSize, Q, comm) baryon.a['S'] = 1.0 baryon.a['P'] = 1.0 state = StateVector(cosmo, {'0': baryon, '1' : cdm}, comm) state.a['S'] = 1.0 state.a['P'] = 1.0 state.save("state")
@MPITest([1, 4]) def test_create(comm): matter = Matter(cosmo, BoxSize, Q, comm)
random_line_split
test_state.py
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM from runtests.mpi import MPITest from nbodykit.cosmology import Planck15 as cosmo import numpy BoxSize = 100. Q = numpy.zeros((100, 3)) @MPITest([1, 4]) def test_create(comm):
matter = Matter(cosmo, BoxSize, Q, comm) cdm = CDM(cosmo, BoxSize, Q, comm) cdm.a['S'] = 1.0 cdm.a['P'] = 1.0 baryon = Baryon(cosmo, BoxSize, Q, comm) baryon.a['S'] = 1.0 baryon.a['P'] = 1.0 state = StateVector(cosmo, {'0': baryon, '1' : cdm}, comm) state.a['S'] = 1.0 state.a['P'] ...
identifier_body
path_utils.rs
use crate::borrow_check::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; use crate::borrow_check::places_conflict; use crate::borrow_check::AccessDepth; use crate::borrow_check::Upvar; use crate::dataflow::indexes::BorrowIndex; use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::Bo...
(place: Place<'_>) -> bool { // Reborrow of already borrowed data is ignored // Any errors will be caught on the initial borrow !place.is_indirect() } /// If `place` is a field projection, and the field is being projected from a closure type, /// then returns the index of the field being projected. Note th...
borrow_of_local_data
identifier_name