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
lars.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(Module): """Layerwise adaptive rate scaling (LARS) optimizer. See https://arxiv.org/abs/1708.03888 """ def __init__(self, vc: VarCollection, momentum: float = 0.9, weight_decay: float = 1e-4, tc: float = 1e-3, eps: float = 1e-5): ...
LARS
identifier_name
lars.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
See https://arxiv.org/abs/1708.03888 """ def __init__(self, vc: VarCollection, momentum: float = 0.9, weight_decay: float = 1e-4, tc: float = 1e-3, eps: float = 1e-5): """Constructor for LARS optimizer. Args: ...
from objax.variable import TrainRef, StateVar, TrainVar, VarCollection class LARS(Module): """Layerwise adaptive rate scaling (LARS) optimizer.
random_line_split
lars.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def __call__(self, lr: float, grads: List[JaxArray]): """Updates variables based on LARS algorithm. Args: lr: learning rate. The LARS paper suggests using lr = lr_0 * (1 -t/T)**2, where t is the current epoch number and T the maximum number of epochs. grads: th...
"""Constructor for LARS optimizer. Args: vc: collection of variables to optimize. momentum: coefficient used for the moving average of the gradient. weight_decay: weight decay coefficient. tc: trust coefficient eta ( < 1) for trust ratio computation. ...
identifier_body
issue-2149.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<B>(&self, f: |A| -> Vec<B> ) { let mut r = fail!(); for elt in self.iter() { r = r + f(*elt); } //~^ ERROR the type of this value must be known } } fn main() { ["hi"].bind(|x| [x] ); //~^ ERROR type `[&str, ..1]` does not implement any method in scope named `bind` }
bind
identifier_name
issue-2149.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ ["hi"].bind(|x| [x] ); //~^ ERROR type `[&str, ..1]` does not implement any method in scope named `bind` }
identifier_body
issue-2149.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut r = fail!(); for elt in self.iter() { r = r + f(*elt); } //~^ ERROR the type of this value must be known } } fn main() { ["hi"].bind(|x| [x] ); //~^ ERROR type `[&str, ..1]` does not implement any method in scope named `bind` }
random_line_split
log_syntax-trace_macros-macro-locations.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { // statements trace_macros!(false); log_syntax!(); // expressions (trace_macros!(false), log_syntax!()); }
random_line_split
log_syntax-trace_macros-macro-locations.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 ...
() { // statements trace_macros!(false); log_syntax!(); // expressions (trace_macros!(false), log_syntax!()); }
main
identifier_name
log_syntax-trace_macros-macro-locations.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 ...
{ // statements trace_macros!(false); log_syntax!(); // expressions (trace_macros!(false), log_syntax!()); }
identifier_body
DepthPassPlugin.js
/** * @author alteredq / http://alteredqualia.com/ */ THREE.DepthPassPlugin = function () { this.enabled = false; this.renderTarget = null; var _gl, _renderer, _lights, _webglObjects, _webglObjectsImmediate, _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new TH...
( object ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ 0 ] : object.material; } };
getObjectMaterial
identifier_name
DepthPassPlugin.js
/** * @author alteredq / http://alteredqualia.com/ */ THREE.DepthPassPlugin = function () { this.enabled = false; this.renderTarget = null; var _gl, _renderer, _lights, _webglObjects, _webglObjectsImmediate, _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new TH...
};
{ return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ 0 ] : object.material; }
identifier_body
DepthPassPlugin.js
/** * @author alteredq / http://alteredqualia.com/ */ THREE.DepthPassPlugin = function () { this.enabled = false; this.renderTarget = null; var _gl, _renderer, _lights, _webglObjects, _webglObjectsImmediate, _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new TH...
_gl.clearColor( 1, 1, 1, 1 ); _gl.disable( _gl.BLEND ); _renderer.state.setDepthTest( true ); // update scene if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum camera.matrixWorldInverse.getInverse( camera.matrixWorld ); _projScreenMatrix.multiplyMat...
// set GL state for depth map
random_line_split
error.rs
use std::path::PathBuf; use std::error::Error; use std::fmt; use super::Environment; use self::ConfigError::*; use term_painter::Color::White; use term_painter::ToStyle; /// The type of a configuration parsing error. #[derive(Debug, PartialEq, Clone)] pub struct ParsingError { /// Start and end byte indices into...
} } /// Whether this error is of `NotFound` variant. #[inline(always)] pub fn is_not_found(&self) -> bool { match *self { NotFound => true, _ => false } } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result...
{ error!("environment variable '{}={}' could not be parsed", White.paint(key), White.paint(value)); info_!("value for {:?} must be {}", White.paint(key), White.paint(expected)) }
conditional_block
error.rs
use std::path::PathBuf; use std::error::Error; use std::fmt; use super::Environment; use self::ConfigError::*; use term_painter::Color::White; use term_painter::ToStyle; /// The type of a configuration parsing error. #[derive(Debug, PartialEq, Clone)] pub struct ParsingError { /// Start and end byte indices into...
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { BadCWD => write!(f, "couldn't get current working directory"), NotFound => write!(f, "config file was not found"), IOError => write!(f, "I/O error while reading the config file"), BadFilePath(ref p, _)...
fmt
identifier_name
error.rs
use std::path::PathBuf; use std::error::Error; use std::fmt; use super::Environment; use self::ConfigError::*; use term_painter::Color::White; use term_painter::ToStyle; /// The type of a configuration parsing error. #[derive(Debug, PartialEq, Clone)] pub struct ParsingError { /// Start and end byte indices into...
error!("configuration file path '{:?}' is invalid", path); info_!("{}", reason); } BadEntry(ref name, ref filename) => { let valid_entries = format!("{}, and global", valid_envs); error!("[{}] is not a known configuration environmen...
NotFound => error!("config file was not found"), IOError => error!("failed reading the config file: IO error"), BadFilePath(ref path, reason) => {
random_line_split
dependency.py
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
process(obj, '_dependencies', _future_dependencies) process(obj, '_optionals', _future_optionals) def requires(*dependencies): """'requires' is a class decorator used to inject providers into consumers. The required providers will be made available to instances of the decorated class via an att...
for dependency in getattr(obj, attr_name, []): if dependency not in REGISTRY: # We don't know about this dependency, so save it for later. unresolved_in_out.setdefault(dependency, []).append(obj) continue setattr(obj, dependency, REGISTRY[dependen...
identifier_body
dependency.py
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
else: raise UnresolvableDependencyException(dependency) for target in targets: setattr(target, dependency, REGISTRY[dependency]) finally: _future_dependencies.clear() return new_providers def reset(): """Reset the registry of provide...
provider = factory() REGISTRY[dependency] = provider new_providers[dependency] = provider
conditional_block
dependency.py
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
(self, name): msg = 'Unregistered dependency: %s' % name super(UnresolvableDependencyException, self).__init__(msg) def provider(name): """'provider' is a class decorator used to register providers. When 'provider' is used to decorate a class, members of that class will register themselve...
__init__
identifier_name
dependency.py
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
# NOTE(morganfainberg): A provider who has an implicit # dependency on other providers may utilize the event callback # mechanism to react to any changes in those providers. This is # performed at the .provider() mechanism so that we can ensure ...
def register_event_callbacks(self):
random_line_split
dialog-ref.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 {OverlayRef, GlobalPositionStrategy, OverlaySizeConfig} from '@angular/cdk/overlay'; import {ESCAPE} from '@a...
/** Fetches the position strategy object from the overlay ref. */ private _getPositionStrategy(): GlobalPositionStrategy { return this._overlayRef.getConfig().positionStrategy as GlobalPositionStrategy; } /** Gets an observable that emits when dialog begins opening. */ beforeOpen(): Observable<void> { ...
{ if (size.width) { this._getPositionStrategy().width(size.width.toString()); } if (size.height) { this._getPositionStrategy().height(size.height.toString()); } this._overlayRef.updateSize(size); this._overlayRef.updatePosition(); return this; }
identifier_body
dialog-ref.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 {OverlayRef, GlobalPositionStrategy, OverlaySizeConfig} from '@angular/cdk/overlay'; import {ESCAPE} from '@a...
(): Observable<void> { return this._containerInstance._beforeEnter.asObservable(); } /** Gets an observable that emits when dialog is finished opening. */ afterOpen(): Observable<void> { return this._containerInstance._afterEnter.asObservable(); } /** Gets an observable that emits when dialog begins...
beforeOpen
identifier_name
dialog-ref.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 {OverlayRef, GlobalPositionStrategy, OverlaySizeConfig} from '@angular/cdk/overlay'; import {ESCAPE} from '@a...
else { strategy.centerVertically(); } this._overlayRef.updatePosition(); return this; } /** * Gets an observable that emits when keydown events are targeted on the overlay. */ keydownEvents(): Observable<KeyboardEvent> { return this._overlayRef.keydownEvents(); } /** * Upda...
{ position.top ? strategy.top(position.top) : strategy.bottom(position.bottom); }
conditional_block
dialog-ref.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 {OverlayRef, GlobalPositionStrategy, OverlaySizeConfig} from '@angular/cdk/overlay'; import {ESCAPE} from '@a...
position.left ? strategy.left(position.left) : strategy.right(position.right); } else { strategy.centerHorizontally(); } if (position && (position.top || position.bottom)) { position.top ? strategy.top(position.top) : strategy.bottom(position.bottom); } else { strategy.centerVer...
let strategy = this._getPositionStrategy(); if (position && (position.left || position.right)) {
random_line_split
colors.js
/** * useful colors for bash */ 'use strict'; module.exports = { black: '\x1b[0;30m', dkgray: '\x1b[1;30m', brick: '\x1b[0;31m', red: '\x1b[1;31m', green: '\x1b[0;32m', lime: '\x1b[1;32m', brown: '\x1b[0;33m', yellow: '\x1b[1;33m', navy: '\x1b[0;34m', blue: '\x1b[1;34m', ...
white: '\x1b[1;37m', reset: '\x1b[0m' };
magenta: '\x1b[1;35m', teal: '\x1b[0;36m', cyan: '\x1b[1;36m', ltgray: '\x1b[0;37m',
random_line_split
theme-context.ts
import { createContext } from 'react'; type Theme = { dark: '#222' | '#fff'; light: '#333' | '#f5f5f5'; darkInversed: '#222' | '#fff'; lightInversed: '#333' | '#f5f5f5'; primary: '#1976d2' | '#90caf9'; danger: '#f56565'; success: '#48bb78'; warning: '#ed8936'; }; const THEME_DARK = 'dark'; const THEME...
const themes: Themes = { [THEME_LIGHT]: { dark: '#fff', darkInversed: '#222', light: '#f5f5f5', lightInversed: '#333', primary: '#1976d2', danger: '#f56565', success: '#48bb78', warning: '#ed8936', }, [THEME_DARK]: { dark: '#222', darkInversed: '#fff', light: '#333', ...
random_line_split
DevLauncher.e2e.ts
import { element, expect, waitFor, by, device } from 'detox'; const MenuTimeout = 70 * 1000; const LauncherMainScreenTimeout = 50 * 1000; const LocalAppTimeout = 80 * 1000; const sleep = (duration: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), duration)); async function pressMenuButton(butt...
await loadButton.multiTap(2); await waitFor(element(by.id('LocalAppMainScreen'))) .toBeVisible() .withTimeout(LocalAppTimeout); await openMenu(); await pressMenuButton('Back to Launcher'); await waitFor(element(by.id('DevLauncherMainScreen'))) .toBeVisible() .withTimeout...
{ // close keyboard await device.pressBack(); }
conditional_block
DevLauncher.e2e.ts
import { element, expect, waitFor, by, device } from 'detox'; const MenuTimeout = 70 * 1000; const LauncherMainScreenTimeout = 50 * 1000; const LocalAppTimeout = 80 * 1000; const sleep = (duration: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), duration)); async function pressMenuButton(butt...
function getInvocationManager() { // @ts-ignore return global.detox[Object.getOwnPropertySymbols(global.detox)[0]]._invocationManager; } function getLocalIPAddress(): string { if (device.getPlatform() === 'ios') { return 'localhost'; } return require('os') .networkInterfaces() .en0.find((elm: {...
{ let button = element(by.text(buttonString)); await waitFor(button).toBeVisible().withTimeout(MenuTimeout); // When we open the dev-menu, we will see an animation. // Unfortunately, if we try to click to button before the // animation finishes, it may not work. We might click different a button. // So tr...
identifier_body
DevLauncher.e2e.ts
import { element, expect, waitFor, by, device } from 'detox'; const MenuTimeout = 70 * 1000; const LauncherMainScreenTimeout = 50 * 1000; const LocalAppTimeout = 80 * 1000; const sleep = (duration: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), duration)); async function pressMenuButton(butt...
() { // @ts-ignore return global.detox[Object.getOwnPropertySymbols(global.detox)[0]]._invocationManager; } function getLocalIPAddress(): string { if (device.getPlatform() === 'ios') { return 'localhost'; } return require('os') .networkInterfaces() .en0.find((elm: { family: string }) => elm.famil...
getInvocationManager
identifier_name
DevLauncher.e2e.ts
import { element, expect, waitFor, by, device } from 'detox'; const MenuTimeout = 70 * 1000; const LauncherMainScreenTimeout = 50 * 1000; const LocalAppTimeout = 80 * 1000; const sleep = (duration: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), duration)); async function pressMenuButton(butt...
await pressMenuButton('Back to Launcher'); await waitFor(element(by.id('DevLauncherMainScreen'))) .toBeVisible() .withTimeout(LauncherMainScreenTimeout); }); });
.withTimeout(LocalAppTimeout); await openMenu();
random_line_split
InfoPanel.tsx
import * as React from "react"; import { connect } from 'react-redux'; import { SkillMapState } from '../store/reducer'; import { ActivityActions } from './ActivityActions'; import { RewardActions } from './RewardActions'; import { MapActions } from './MapActions'; import { ActivityStatus, isActivityUnlocked, isMapUn...
if (map) subtitle = map.displayName } else if (user) { // Count of completed activities (not including reward nodes) const mapIds = Object.keys(maps); let completed = 0; let total = 0; let completedRewards = 0; let totalRewards...
{ details.push(maxSteps ? `${currentStep}/${maxSteps} ${lf("Steps")}` : lf("Not Started")); details.push(isActivity ? (node as MapActivity).type : ""); }
conditional_block
InfoPanel.tsx
import * as React from "react"; import { connect } from 'react-redux'; import { SkillMapState } from '../store/reducer'; import { ActivityActions } from './ActivityActions'; import { RewardActions } from './RewardActions'; import { MapActions } from './MapActions'; import { ActivityStatus, isActivityUnlocked, isMapUn...
{isMap && infoUrl && <a className="info-panel-link" href={infoUrl} target="_blank" rel="noopener noreferrer">{lf("Learning Outcomes")} </a>} {tags && tags.length > 0 && <div className="info-panel-tags"> {tags.map((el, i) => <div key={i}>{el}</div>)} </...
{ const { mapId, title, subtitle, description, infoUrl, imageUrl, details, node, status, completedHeaderId } = this.props; const statusLabel = this.getStatusLabel(status); const isMap = !node; const isActivity = node && !isRewardNode(node); const tags = isActivity && (node as M...
identifier_body
InfoPanel.tsx
import * as React from "react"; import { connect } from 'react-redux'; import { SkillMapState } from '../store/reducer'; import { ActivityActions } from './ActivityActions'; import { RewardActions } from './RewardActions'; import { MapActions } from './MapActions'; import { ActivityStatus, isActivityUnlocked, isMapUn...
{tags && tags.length > 0 && <div className="info-panel-tags"> {tags.map((el, i) => <div key={i}>{el}</div>)} </div>} <div className="info-panel-detail"> {details?.map((el, i) => <div key={`detail_${i}`}>{el}</div>)} ...
</div>} <div className="info-panel-description">{description}</div> {isMap && infoUrl && <a className="info-panel-link" href={infoUrl} target="_blank" rel="noopener noreferrer">{lf("Learning Outcomes")}</a>}
random_line_split
InfoPanel.tsx
import * as React from "react"; import { connect } from 'react-redux'; import { SkillMapState } from '../store/reducer'; import { ActivityActions } from './ActivityActions'; import { RewardActions } from './RewardActions'; import { MapActions } from './MapActions'; import { ActivityStatus, isActivityUnlocked, isMapUn...
() { const { mapId, title, subtitle, description, infoUrl, imageUrl, details, node, status, completedHeaderId } = this.props; const statusLabel = this.getStatusLabel(status); const isMap = !node; const isActivity = node && !isRewardNode(node); const tags = isActivity && (node a...
render
identifier_name
sensor.py
"""Support for Z-Wave sensors.""" from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect ...
@property def native_unit_of_measurement(self): """Return the unit of measurement the value is expressed in.""" return self._units class ZWaveMultilevelSensor(ZWaveSensor): """Representation of a multi level sensor Z-Wave sensor.""" @property def native_value(self): """Ret...
random_line_split
sensor.py
"""Support for Z-Wave sensors.""" from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect ...
@property def force_update(self): """Return force_update.""" return True @property def native_value(self): """Return the state of the sensor.""" return self._state @property def native_unit_of_measurement(self): """Return the unit of measurement the va...
"""Handle the data changes for node values.""" self._state = self.values.primary.data self._units = self.values.primary.units
identifier_body
sensor.py
"""Support for Z-Wave sensors.""" from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect ...
(self): """Return the unit of measurement the value is expressed in.""" return self._units class ZWaveMultilevelSensor(ZWaveSensor): """Representation of a multi level sensor Z-Wave sensor.""" @property def native_value(self): """Return the state of the sensor.""" if self....
native_unit_of_measurement
identifier_name
sensor.py
"""Support for Z-Wave sensors.""" from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect ...
return self._units class ZWaveAlarmSensor(ZWaveSensor): """Representation of a Z-Wave sensor that sends Alarm alerts. Examples include certain Multisensors that have motion and vibration capabilities. Z-Wave defines various alarm types such as Smoke, Flood, Burglar, CarbonMonoxide, etc. ...
return TEMP_FAHRENHEIT
conditional_block
ohai.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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...
main()
conditional_block
ohai.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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...
# import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
module = AnsibleModule( argument_spec = dict() ) cmd = ["/usr/bin/env", "ohai"] rc, out, err = module.run_command(cmd, check_rc=True) module.exit_json(**json.loads(out))
identifier_body
ohai.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public L...
# it under the terms of the GNU General Public License as published by
random_line_split
ohai.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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...
(): module = AnsibleModule( argument_spec = dict() ) cmd = ["/usr/bin/env", "ohai"] rc, out, err = module.run_command(cmd, check_rc=True) module.exit_json(**json.loads(out)) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
main
identifier_name
memory.py
# (c) 2014, Brian Coca, Josh Drake, et al # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' cache: memory short_description: RAM ba...
def flush(self): self._cache = {} def copy(self): return self._cache.copy() def __getstate__(self): return self.copy() def __setstate__(self, data): self._cache = data
del self._cache[key]
identifier_body
memory.py
# (c) 2014, Brian Coca, Josh Drake, et al # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' cache: memory short_description: RAM ba...
def __init__(self, *args, **kwargs): self._cache = {} def get(self, key): return self._cache.get(key) def set(self, key, value): self._cache[key] = value def keys(self): return self._cache.keys() def contains(self, key): return key in self._cache def...
class CacheModule(BaseCacheModule):
random_line_split
memory.py
# (c) 2014, Brian Coca, Josh Drake, et al # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' cache: memory short_description: RAM ba...
(self): return self.copy() def __setstate__(self, data): self._cache = data
__getstate__
identifier_name
player.ts
export const player = { state: { streamUrl: null, chapter: null, book: null, totalTime: 0, paused: false, currentTime: 0, repeat: true, volume: 75, }, reducers: { setStreamUrl(state, payload) { return { ...state, streamUrl: payload }; }, setChapter(state, payload)...
, setTotalTime(state, payload) { return { ...state, totalTime: payload }; }, setCurrentTime(state, payload) { return { ...state, currentTime: payload }; }, setTime(state, payload) { return { ...state, totalTime: payload.totalTime, currentTime: payload.currentTime }; }, setV...
{ return { ...state, paused: payload }; }
identifier_body
player.ts
export const player = { state: { streamUrl: null, chapter: null, book: null, totalTime: 0, paused: false, currentTime: 0, repeat: true, volume: 75, }, reducers: { setStreamUrl(state, payload) { return { ...state, streamUrl: payload }; }, setChapter(state, payload)...
this.setPaused(false); this.setBook(null); this.setChapter(null); this.setStreamUrl(null); }, }, }; export default player;
this.setChapter(activeChapter); this.setPaused(false); this.setStreamUrl(streamUrl); }, close() {
random_line_split
player.ts
export const player = { state: { streamUrl: null, chapter: null, book: null, totalTime: 0, paused: false, currentTime: 0, repeat: true, volume: 75, }, reducers: { setStreamUrl(state, payload) { return { ...state, streamUrl: payload }; }, setChapter(state, payload)...
(state, payload) { return { ...state, repeat: payload }; }, }, effects: { playCurrentChapter(payload, rootState) { const { activeBook, activeChapter, activeVersion } = rootState.bible; const streamUrl = PlayerUtils.getStreamUrl(activeBook, activeChapter, activeVersion); this.setBook(...
setRepeat
identifier_name
Sider.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Menu, Icon } from 'antd' import { fetchData } from '../actions/Sider' import { Link } from 'react-router' const SubMenu = Menu.SubMenu const MenuItemGroup = Menu.ItemGroup const mapStateT...
componentWillMount () { this.props.fetchData() } handleClick (e) { console.log('click ', e) this.setState({ current: e.key }) } render () { var subTag = 0 var itemTag = 0 var optionTag = 0 return ( <Menu onClick={this.handleClick.bind(this)} defaultOpenK...
{ super(props) this.state = { current: '1' } }
identifier_body
Sider.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Menu, Icon } from 'antd' import { fetchData } from '../actions/Sider' import { Link } from 'react-router' const SubMenu = Menu.SubMenu const MenuItemGroup = Menu.ItemGroup const mapStateT...
extends Component { static propTypes = { fetchData: React.PropTypes.func.isRequired, siderData: React.PropTypes.array.isRequired } constructor (props) { super(props) this.state = { current: '1' } } componentWillMount () { this.props.fetchData() } handleClick (e) { con...
Sider
identifier_name
Sider.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Menu, Icon } from 'antd' import { fetchData } from '../actions/Sider' import { Link } from 'react-router' const SubMenu = Menu.SubMenu const MenuItemGroup = Menu.ItemGroup const mapStateT...
else if (item.type === 'drop') { return (<SubMenu key={'item' + itemTag++} title={item.title}> {item.children && item.children.map((option, index) => ( <Menu.Item key={'option' + optionTag++}><Link to={option.url}>{option.title}</Link></Menu.Item> ...
{ return (<MenuItemGroup key={'item' + itemTag++} title={item.title}> {item.children && item.children.map((option, index) => ( <Menu.Item key={'option' + optionTag++}><Link to={option.url}>{option.title}</Link></Menu.Item> ))} </Men...
conditional_block
Sider.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Menu, Icon } from 'antd' import { fetchData } from '../actions/Sider' import { Link } from 'react-router' const SubMenu = Menu.SubMenu const MenuItemGroup = Menu.ItemGroup const mapStateT...
static propTypes = { fetchData: React.PropTypes.func.isRequired, siderData: React.PropTypes.array.isRequired } constructor (props) { super(props) this.state = { current: '1' } } componentWillMount () { this.props.fetchData() } handleClick (e) { console.log('click ', e)...
} class Sider extends Component {
random_line_split
file.js
// this._write(output, callback); this._size += output.length; this._lazyDrain(); } else { this.open(function (err) { if (err) { // // If there was an error enqueue the message // return self._buffer.push([output, callback]); } self._write(output, ...
random_line_split
file.js
this.timestamp = options.timestamp != null ? options.timestamp : true; this.eol = options.eol || '\n'; this.tailable = options.tailable || false; this.depth = options.depth || null; this.showLevel = options.showLevel === undefined ? true : options.showLevel; if (this.json) { ...
var self = this; if (typeof msg !== 'string') { msg = '' + msg; } var output = common.log({ level: level, message: msg, meta: meta, json: this.json, logstash: this.logstash, colorize: this.colorize, prettyPrint: this.prettyPrint, timestamp: ...
{ return callback(null, true); }
conditional_block
file.js
(target /*, illegal... */) { Array.prototype.slice.call(arguments, 1).forEach(function (name) { if (options[name]) { throw new Error('Cannot set ' + name + ' and ' + target + 'together'); } }); } if (options.filename || options.dirname) { throwIf('filename or dirname', 'stream'); ...
throwIf
identifier_name
file.js
this.timestamp = options.timestamp != null ? options.timestamp : true; this.eol = options.eol || '\n'; this.tailable = options.tailable || false; this.depth = options.depth || null; this.showLevel = options.showLevel === undefined ? true : options.showLevel; if (this.json) { ...
function push(log) { if (options.rows && results.length >= options.rows) { if (stream.readable) { stream.destroy(); } return; } if (options.fields) { var obj = {}; options.fields.forEach(function (key) { obj[key] = log[key]; }); log = obj; }...
{ try { var log = JSON.parse(buff); if (check(log)) push(log); } catch (e) { if (!attempt) { stream.emit('error', e); } } }
identifier_body
ConnectedNode.js
goog.provide('crow.ConnectedNode'); goog.require('crow.Node'); /** * ConnectedNodes are nodes that have to be explicitly "connected" to other nodes. * @class */ crow.ConnectedNode = function(id){ crow.Node.apply(this, arguments); this.connections = []; this.connectionDistances = {}; }; crow.ConnectedNode.protot...
}; crow.ConnectedNode.prototype.getNeighbors = function(){ return this.connections; }; crow.ConnectedNode.prototype.distanceToNeighbor = function(otherNode){ return this.connectionDistances[otherNode.id] || Infinity; }
{ otherNode.connections.push(this); otherNode.connectionDistances[this.id] = distance; }
conditional_block
ConnectedNode.js
goog.provide('crow.ConnectedNode'); goog.require('crow.Node'); /** * ConnectedNodes are nodes that have to be explicitly "connected" to other nodes. * @class */ crow.ConnectedNode = function(id){ crow.Node.apply(this, arguments);
if(typeof distance == "undefined") distance = 1; this.connections.push(otherNode); this.connectionDistances[otherNode.id] = distance; if(typeof symmetric !== "false" && otherNode instanceof crow.ConnectedNode){ otherNode.connections.push(this); otherNode.connectionDistances[this.id] = distance; } }; crow.Conne...
this.connections = []; this.connectionDistances = {}; }; crow.ConnectedNode.prototype = new crow.Node(); crow.ConnectedNode.prototype.connectTo = function(otherNode, distance, symmetric){
random_line_split
cart-view.js
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
}
{ this._cart = cart; }
identifier_body
cart-view.js
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
() { // Remove existing products let itemRows = this._tbody.querySelectorAll(this.itemSelector); for (let i = 0; i < itemRows.length; i++) { this._tbody.removeChild(itemRows[i]); } for (let item of this._cart.cart) { let product = findProduct(item.sku); let placeholder = document.c...
render
identifier_name
cart-view.js
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
this.updateTotal(); } _goToPayment() { pushLocationHash('pay'); } _handleClick(event) { if (event.target.dataset) { var sku = event.target.dataset.sku; var action = event.target.dataset.action; if (sku && action == 'remove') { var product = this._cart.findItem(sku); ...
{ row.parentNode.removeChild(row); }
conditional_block
cart-view.js
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software 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 Vi...
http://www.apache.org/licenses/LICENSE-2.0
random_line_split
data.js
var dl = require('datalib'), log = require('vega-logging'), parseTransforms = require('./transforms'), parseModify = require('./modify'); function parseData(model, spec, callback) { var config = model.config(), count = 0; function onError(error, d) { log.error('PARSE DATA FAILED: ' + d.name ...
}, "additionalProperties": false }] } }, "required": ["name"] }, { "anyOf": [{ "required": ["name", "modify"] }, { "oneOf": [{ "properties": {"source": {"type": "string"}}, "required": ["s...
}, { "properties": { "type": {"enum": ["treejson"]}, "children": {"type": "string"}, "parse": parseDef
random_line_split
data.js
var dl = require('datalib'), log = require('vega-logging'), parseTransforms = require('./transforms'), parseModify = require('./modify'); function parseData(model, spec, callback) { var config = model.config(), count = 0; function onError(error, d) { log.error('PARSE DATA FAILED: ' + d.name ...
// process each data set definition (spec || []).forEach(function(d) { if (d.url) { count += 1; dl.load(dl.extend({url: d.url}, config.load), onLoad(d)); } try { parseData.datasource(model, d); } catch (err) { onError(err, d); } }); if (count === 0) setTimeout(call...
{ return function(error, data) { if (error) { onError(error, d); } else if (count > 0) { try { model.data(d.name).values(dl.read(data, d.format)); if (--count === 0) callback(); } catch (err) { onError(err, d); } } }; }
identifier_body
data.js
var dl = require('datalib'), log = require('vega-logging'), parseTransforms = require('./transforms'), parseModify = require('./modify'); function parseData(model, spec, callback) { var config = model.config(), count = 0; function
(error, d) { log.error('PARSE DATA FAILED: ' + d.name + ' ' + error); count = -1; callback(error); } function onLoad(d) { return function(error, data) { if (error) { onError(error, d); } else if (count > 0) { try { model.data(d.name).values(dl.read(data, d.form...
onError
identifier_name
directions.py
# Copyright (c) 2015, Lars Tingelstad # All rights reserved. # # All rights reserved. # Redistribution and use 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 # l...
# * Neither the name of pyversor nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ...
random_line_split
mode.rs
use state::State; use std::marker::PhantomData; use typeahead::Parse; pub trait Transition<K> where K: Ord, K: Copy, K: Parse, { fn name(&self) -> &'static str; fn transition(&self, state: &mut State<K>) -> Mode<K>; } #[derive(Clone, Copy, Debug)] pub struct NormalMode<K> { t: PhantomData<K>, ...
<K> { Normal(NormalMode<K>), Pending(PendingMode<K>), Insert(InsertMode<K>), } pub fn normal<K>() -> Mode<K> { Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} }) } pub fn recast_normal<K>(orig: &NormalMode<K>) -> Mode<K> { Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} }) } pub fn pe...
Mode
identifier_name
mode.rs
use state::State; use std::marker::PhantomData; use typeahead::Parse; pub trait Transition<K> where K: Ord, K: Copy,
{ fn name(&self) -> &'static str; fn transition(&self, state: &mut State<K>) -> Mode<K>; } #[derive(Clone, Copy, Debug)] pub struct NormalMode<K> { t: PhantomData<K>, } /// Used by `PendingMode` to remember what mode to transition to next. #[derive(Clone, Copy, Debug)] pub enum NextMode { Normal, ...
K: Parse,
random_line_split
mode.rs
use state::State; use std::marker::PhantomData; use typeahead::Parse; pub trait Transition<K> where K: Ord, K: Copy, K: Parse, { fn name(&self) -> &'static str; fn transition(&self, state: &mut State<K>) -> Mode<K>; } #[derive(Clone, Copy, Debug)] pub struct NormalMode<K> { t: PhantomData<K>, ...
pub fn insert<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: false, }) } pub fn replace<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: true, }) } impl<K> Transition<K> for Mode<K> where ...
{ Mode::Pending(PendingMode::<K> { t: PhantomData::<K> {}, next_mode: orig.next_mode, }) }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
} } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<Co...
{ m.reply(&format!("Error: {:?}", err)); }
conditional_block
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispat...
start
identifier_name
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
}
{ match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
} pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn start(&mut self) { ...
sender: None }
random_line_split
material.rs
, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, Rock = 3, RockSteep = 4,
struct MaterialTypeRaw(MaterialType); impl WebAsset for MaterialTypeRaw { type Type = MaterialRaw; fn url(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = ma...
}
random_line_split
material.rs
, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, Rock = 3, RockSteep = 4, } struct MaterialTypeRaw(MaterialType); impl WebAsset for MaterialTypeRaw { type Type = MaterialRaw; fn
(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = match self.0 { _ => "terrain.zip", }; format!("materials/raw/{}", name) } fn par...
url
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
(s: &str) -> Result<RequestUri, HttpError> { match s.as_bytes() { [] => Err(HttpError::HttpUriError(UrlError::InvalidCharacter)), [b'*'] => Ok(RequestUri::Star), [b'/', ..] => Ok(RequestUri::AbsolutePath(s.to_string())), bytes if bytes.contains(&b'/') => { ...
from_str
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
/// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` #[derive(Debug, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. //...
/// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy.
random_line_split
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
} } } #[test] fn test_uri_fromstr() { use error::HttpResult; fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(s.parse(), result); } read("*", Ok(RequestUri::Star)); read("http://hyper.rs/", Ok(RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); ...
{ let mut temp = "http://".to_string(); temp.push_str(s); try!(Url::parse(&temp[..])); todo!("compare vs u.authority()"); Ok(RequestUri::Authority(s.to_string())) }
conditional_block
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, opt...
if folded == Any && shapes.iter().any(|s| s != &Any) { generate_tuple_type(ctxt, path, shapes) } else { generate_vec_type(ctxt, path, &folded) } } VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e), Struct { fields: r...
let folded = shape::fold_shapes(shapes.clone());
random_line_split
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct
{ options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) { let mut ctxt = Ctxt { options }; let ident = "".to_string(); let value = type_from_shape(&mut ctxt, name, shape); let code = ::serde...
Ctxt
identifier_name
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, opt...
fn collapse_option(typ: &Shape) -> (bool, &Shape) { if let Shape::Optional(inner) = typ { return (true, &**inner); } (false, typ) } fn generate_struct_from_field_shapes( ctxt: &mut Ctxt, _path: &str, map: &LinkedHashMap<String, Shape>, ) -> Value { let mut properties = json!({}); ...
{ let mut types = Vec::new(); for shape in shapes { let typ = type_from_shape(ctxt, path, shape); types.push(typ); } json!({ "__type__": "tuple", "items": types, }) }
identifier_body
index.js
(function () { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), img = document.createElement("img"); canvas.width = 512; canvas.height = 512; context.fillStyle = "white"; context.fillRect( 0, 0, canvas.width, canvas.height ); document.body.style...
// To enable drag and drop canvas.addEventListener("dragover", function (evt) { evt.preventDefault(); }, false); // Handle dropped image file - only Firefox and Google Chrome canvas.addEventListener("drop", function (evt) { var files = evt.dataTransfer.files; if (files....
random_line_split
index.js
(function () { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), img = document.createElement("img"); canvas.width = 512; canvas.height = 512; context.fillStyle = "white"; context.fillRect( 0, 0, canvas.width, canvas.height ); document.body.style...
} context.putImageData( imageData, 0, 0 ); }, false); // To enable drag and drop canvas.addEventListener("dragover", function (evt) { evt.preventDefault(); }, false); // Handle dropped image file - only Firefox and Google Chrome canvas.addEventListener("drop", ...
{ for(let x = 0; x<img.width; x++){ const pixelOffset = (y * img.width + x) * 4; /* * For now just flip the y component, this will be used for converting normal maps * from my old demo to use the standard normal map coordinates. ...
conditional_block
tools.py
''' base tools ''' # -*- coding: utf-8 -*- import re def
(ip) : pattern = r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$' matcher = re.match(pattern, ip) if matcher is not None : return True return False def is_domain(domain) : pattern = r'[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9...
is_ipv4
identifier_name
tools.py
''' base tools ''' # -*- coding: utf-8 -*- import re def is_ipv4(ip) :
def is_domain(domain) : pattern = r'[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?' matcher = re.match(pattern, domain) if matcher is not None : return True return False
pattern = r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$' matcher = re.match(pattern, ip) if matcher is not None : return True return False
identifier_body
tools.py
''' base tools ''' # -*- coding: utf-8 -*- import re def is_ipv4(ip) : pattern = r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$' matcher = re.match(pattern, ip) if matcher is not None : return True return False def is_domain(domain) : ...
return False
if matcher is not None : return True
random_line_split
tools.py
''' base tools ''' # -*- coding: utf-8 -*- import re def is_ipv4(ip) : pattern = r'^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$' matcher = re.match(pattern, ip) if matcher is not None : return True return False def is_domain(domain) : ...
return False
return True
conditional_block
bpscore_benchmark.py
#!/usr/bin/env python3 # # This script executes different GO BPScore algorithms # in order to compare their run times. # for timing import time # for the data connection import pappi.sql from pappi.data_config import * # import the GO association loading function from pappi.go.utils import load_go_associations_sql ...
print("loading benchmarking class...") benchmarker = BPScore_Benchmarker() print("benchmark init times...") benchmarker.init_scorers() print("benchmark scoring...") benchmarker.run_benchmark() # print the actual timing results benchmarker.print_timings()
conditional_block
bpscore_benchmark.py
#!/usr/bin/env python3 # # This script executes different GO BPScore algorithms # in order to compare their run times. # for timing import time # for the data connection import pappi.sql from pappi.data_config import * # import the GO association loading function from pappi.go.utils import load_go_associations_sql ...
def run_benchmark(self): for n in range(10, 1001, 10): print("benchmarking for n = " + str(n) + " genes...") self.benchmark_scorers(n) def print_timings(self): print("scored by " + str(len(self.scorers)) + " scorers") print() print("n\t" + "\t".join(sel...
assoc = load_go_associations_sql(sql_conn) # use a list for fast/efficient range access genes = list(assoc.keys()) return genes
identifier_body
bpscore_benchmark.py
#!/usr/bin/env python3 # # This script executes different GO BPScore algorithms # in order to compare their run times. # for timing import time # for the data connection import pappi.sql from pappi.data_config import * # import the GO association loading function from pappi.go.utils import load_go_associations_sql ...
(self): # get database connection self.con = pappi.sql.get_conn(DATABASE) self.genes = self.get_benchmark_genes(self.con) self.scorers = [] self.init_time = [] self.run_times = dict() # dict {number of genes -> list of run times} def init_scorers(self): # in...
__init__
identifier_name
bpscore_benchmark.py
#!/usr/bin/env python3 # # This script executes different GO BPScore algorithms # in order to compare their run times. # for timing import time # for the data connection import pappi.sql from pappi.data_config import * # import the GO association loading function from pappi.go.utils import load_go_associations_sql ...
class BPScore_Benchmarker: def __init__(self): # get database connection self.con = pappi.sql.get_conn(DATABASE) self.genes = self.get_benchmark_genes(self.con) self.scorers = [] self.init_time = [] self.run_times = dict() # dict {number of genes -> list of run times...
random_line_split
blip.component.ts
b.order }); let ringRadiusTotal = this.cycles.reduce((previous, current) => { return previous + current.size; }, 0); let innerRadius = 0, outerRadius = 0, ringSizeSum = 0; this.cycles.forEach((cycle) => { ...
return 1; }
conditional_block
blip.component.ts
private readonly parentNativeElement: any; private d3Svg: any; private mouseOnBlip: Blip; private radius: number; private tooltip: any; private soloQuadrant: Quadrant; private readonly activatedBlipEventName = "activated.blip"; constructor(element: ElementRef, private radarService...
ycle: Cycle, radii: IRange, blips: Blip[]) { let blipA = this.d3Svg.append("g").selectAll("a") .data(blips).enter() .append("a") .attr("class", "blip-group") .attr("placement", "top") .attr("container", "body") .attr("opacity", ...
eateBlipsByCycle(c
identifier_name
blip.component.ts
private readonly parentNativeElement: any; private d3Svg: any; private mouseOnBlip: Blip; private radius: number; private tooltip: any; private soloQuadrant: Quadrant; private readonly activatedBlipEventName = "activated.blip"; constructor(element: ElementRef, private radarServ...
.attr("opacity", "1"); } private buildPolygonItem(element: any) { return element .filter((blip: Blip) => { return blip.isNew }) .append("polygon") .attr("points", (blip: Blip) => { return this.trianglePoints(blip); }) .attr("class", (blip: Bli...
.attr("cx", "0") .attr("cy", "4") .attr("class", (blip: Blip) => { return this.getBlipClassNameByQuadrantId(blip.quadrantId) }) .attr("stroke-width", "1.5") .attr("r", (blip: Blip) => { return (this.radar.sized ? (2 * (2 ^ blip.size)) + 10 : 11); })
random_line_split
blip.component.ts
private readonly parentNativeElement: any; private d3Svg: any; private mouseOnBlip: Blip; private radius: number; private tooltip: any; private soloQuadrant: Quadrant; private readonly activatedBlipEventName = "activated.blip"; constructor(element: ElementRef, private radarServ...
case 3: adjustments = { x: 1, y: 1 }; chartCenter = { x: 0, y: 0 }; break; case 4: adjustments = { x: -1, y: 1 }; chartCenter = { x: this.radius, y: 0 }; break; default: adjustments = { x: 1, y: 1 }; ...
let adjustments: { x: number; y: number }; let chartCenter: { x: number; y: number }; let quadrant = this.radar.findQuadrantById(blip.quadrantId); if (quadrant == null) { return null; } switch (quadrant.quadrantNumber) { case 1: adjustme...
identifier_body
PurchaseButton.tsx
import * as React from "react"; import { IProductState } from "types"; import { Button } from "components";
purchaseState: string; accountBalance: number; onPurchase: Function; } export default class PurchaseButton extends React.Component<IPurchaseButtonProps> { render() { const { products, purchaseState, accountBalance, onPurchase } = this.props; const total = products.products.filter((prod...
import * as style from "styles/primary/components/PurchaseButton.scss"; interface IPurchaseButtonProps { products: IProductState;
random_line_split
PurchaseButton.tsx
import * as React from "react"; import { IProductState } from "types"; import { Button } from "components"; import * as style from "styles/primary/components/PurchaseButton.scss"; interface IPurchaseButtonProps { products: IProductState; purchaseState: string; accountBalance: number; onPurchase: Func...
} return ( <Button label={total + " kr"} icon="shopping-cart" className={style.button} disabled={!active} success={active} alert={alert} onClick={onPurchase}/> ); } }...
{ alert = true; }
conditional_block
PurchaseButton.tsx
import * as React from "react"; import { IProductState } from "types"; import { Button } from "components"; import * as style from "styles/primary/components/PurchaseButton.scss"; interface IPurchaseButtonProps { products: IProductState; purchaseState: string; accountBalance: number; onPurchase: Func...
extends React.Component<IPurchaseButtonProps> { render() { const { products, purchaseState, accountBalance, onPurchase } = this.props; const total = products.products.filter((product) => { return !product.loading && !product.failed; }).map((product) => { return prod...
PurchaseButton
identifier_name
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } ...
let www = req.headers().get_str(authorization); let auth = match www_base64_to_auth(www) { Ok(a) => a, Err(e) => return Err(f(e)), }; debug!("addr: {}, www: {}, auth: {:?}", addr, www, auth); if auth != self.auth { return Err(f("wrong usernam...
{ // info!("url: {:?}", req.uri()); // info!("header: {:?}", req.headers()); let method_is_proxy = method_maybe_proxy(req).is_some(); let (authorization, code, authenticate) = if method_is_proxy { (header::PROXY_AUTHORIZATION, 407, header::PROXY_AUTHENTICATE) } else...
identifier_body
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } ...
(value: &str) -> Result<Auth, &'static str> { let value = value.trim(); if value.len() <= "basic".len() || value[0.."basic".len()].to_lowercase() != "basic" { return Err("not basic"); } let value = (&value["basic".len()..]).trim(); decode_config(value, URL_SAFE) .map_err(|_| "inva...
www_base64_to_auth
identifier_name
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth,
impl Authenticator { pub fn new(auth: Auth) -> Self { Self { auth } } } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication // HTTP/1.0 401 Authorization Required // WWW-Authenticate: Basic realm="Secure Area" // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // tips: base64encode(...
}
random_line_split