file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
mod.rs
extern crate bip_metainfo; extern crate bip_disk; extern crate bip_util; extern crate bytes; extern crate futures; extern crate tokio_core; extern crate rand; use std::collections::HashMap; use std::io::{self}; use std::path::{Path, PathBuf}; use std::sync::{Mutex, Arc}; use std::cmp; use std::time::Duration; use bip...
() -> InMemoryFileSystem { InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) } } pub fn run_with_lock<C, R>(&self, call: C) -> R where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R { let mut lock_files = self.files.lock().unwrap(); call(&mut *lock_files) } } ...
new
identifier_name
mod.rs
extern crate bip_metainfo; extern crate bip_disk; extern crate bip_util; extern crate bytes; extern crate futures; extern crate tokio_core; extern crate rand; use std::collections::HashMap; use std::io::{self}; use std::path::{Path, PathBuf}; use std::sync::{Mutex, Arc}; use std::cmp; use std::time::Duration; use bip...
} struct InMemoryFile { path: PathBuf } impl FileSystem for InMemoryFileSystem { type File = InMemoryFile; fn open_file<P>(&self, path: P) -> io::Result<Self::File> where P: AsRef<Path> + Send + 'static { let file_path = path.as_ref().to_path_buf(); self.run_with_lock(|files| {...
{ let mut lock_files = self.files.lock().unwrap(); call(&mut *lock_files) }
identifier_body
mod.rs
extern crate bip_metainfo; extern crate bip_disk; extern crate bip_util; extern crate bytes; extern crate futures; extern crate tokio_core; extern crate rand; use std::collections::HashMap; use std::io::{self}; use std::path::{Path, PathBuf}; use std::sync::{Mutex, Arc}; use std::cmp; use std::time::Duration; use bip...
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len()); if bytes_to_copy != 0 { file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer); } // TODO...
{ file_buffer.resize(last_byte_pos, 0); }
conditional_block
setup_matrix_multiply.py
''' SASSIE Copyright (C) 2011 Joseph E. Curtis This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you are welcome to redistribute it under certain conditions; see http://www.gnu.org/licenses/gpl-3.0.html for details. ''' # System imports from distutils.core import * from distut...
import numpy from numpy.distutils.core import Extension, setup # Obtain the numpy include directory. This logic works across numpy versions. try: numpy_include = numpy.get_include() except AttributeError: numpy_include = numpy.get_numpy_include() # simple extension module matrix_math = Extension(name="matr...
random_line_split
transfer.py
#!/usr/bin/env python ''' Copyright (C) 2013, Digium, Inc. Matt Jordan <mjordan@digium.com> This program is free software, distributed under the terms of the GNU General Public License Version 2. ''' import sys import logging sys.path.append("lib/python") from version import AsteriskVersion LOGGER = logging.getLogg...
(self, ami, event): ''' Handle the AttendedTransfer event. Once the event has triggered, the call can be torn down. ''' LOGGER.debug('ami %d: received event %s' % (ami.id, event)) self._handle_feature_end(None, None) def complete_attended_transfer(self): ''' Called w...
_handle_attended_transfer
identifier_name
transfer.py
#!/usr/bin/env python ''' Copyright (C) 2013, Digium, Inc. Matt Jordan <mjordan@digium.com> This program is free software, distributed under the terms of the GNU General Public License Version 2. ''' import sys import logging sys.path.append("lib/python") from version import AsteriskVersion LOGGER = logging.getLogg...
''' Callback that occurs during an attended transfer. This callback signals that the test should complete the attended transfer by hanging up the transferer. ''' LOGGER.debug('ami %d: received event %s' % (ami.id, event)) transfer = Transfer.get_instance() transfer.complete_attended_transfe...
identifier_body
transfer.py
#!/usr/bin/env python ''' Copyright (C) 2013, Digium, Inc. Matt Jordan <mjordan@digium.com> This program is free software, distributed under the terms of the GNU General Public License Version 2. ''' import sys import logging sys.path.append("lib/python") from version import AsteriskVersion LOGGER = logging.getLogg...
else: self.test_object.register_feature_end_observer(self._handle_feature_end) if (Transfer.__singleton_instance == None): Transfer.__singleton_instance = self def _handle_ami_connect(self, ami): ''' Handle AMI connect events ''' if (ami.id != 0): ...
self.test_object.register_ami_observer(self._handle_ami_connect)
conditional_block
transfer.py
#!/usr/bin/env python ''' Copyright (C) 2013, Digium, Inc. Matt Jordan <mjordan@digium.com> This program is free software, distributed under the terms of the GNU General Public License Version 2. ''' import sys import logging sys.path.append("lib/python") from version import AsteriskVersion LOGGER = logging.getLogg...
''' Callback for the BridgeTestCase feature detected event Keyword Arguments: test_object The BridgeTestCase object feature The specific feature that was executed ''' LOGGER.debug('Setting current feature to %s' % str(feature)) self._current_feature = feature ...
def _handle_feature_start(self, test_object, feature):
random_line_split
dumbmap.ts
/** * This is a really dumb O(n) implementation of a map, because I was * having issues with TS and the native ES6 map. * * TODO(cleanup): remove this for just a normal ES6 Map. */ export class DumbMap<V> implements Map<any, V> { private _dumbArray: Array<DumbKey<V>> = new Array<DumbKey<V>>(); clear() { this....
private _findIndex(key: any): number { for (let i = 0, q = this._dumbArray.length; i < q; i++) { if (this._dumbArray[i].key === key) { return i; } } return -1; } } class DumbKey<V> { constructor(public key: any, public value: V) {} }
{ return this._dumbArray.length; }
identifier_body
dumbmap.ts
/** * This is a really dumb O(n) implementation of a map, because I was * having issues with TS and the native ES6 map. * * TODO(cleanup): remove this for just a normal ES6 Map. */ export class DumbMap<V> implements Map<any, V> { private _dumbArray: Array<DumbKey<V>> = new Array<DumbKey<V>>(); clear() { this....
return this; } entries(): Iterator<[any, V]> { throw new Error('Unsupported Operation.'); } keys(): Iterator<any> { throw new Error('Unsupported Operation.'); } values(): Iterator<V> { throw new Error('Unsupported Operation.'); } get size(): number { return this._dumbArray.length; } private _findIn...
}
random_line_split
dumbmap.ts
/** * This is a really dumb O(n) implementation of a map, because I was * having issues with TS and the native ES6 map. * * TODO(cleanup): remove this for just a normal ES6 Map. */ export class DumbMap<V> implements Map<any, V> { private _dumbArray: Array<DumbKey<V>> = new Array<DumbKey<V>>(); clear() { this....
(): number { return this._dumbArray.length; } private _findIndex(key: any): number { for (let i = 0, q = this._dumbArray.length; i < q; i++) { if (this._dumbArray[i].key === key) { return i; } } return -1; } } class DumbKey<V> { constructor(public key: any, public value: V) {} }
size
identifier_name
dumbmap.ts
/** * This is a really dumb O(n) implementation of a map, because I was * having issues with TS and the native ES6 map. * * TODO(cleanup): remove this for just a normal ES6 Map. */ export class DumbMap<V> implements Map<any, V> { private _dumbArray: Array<DumbKey<V>> = new Array<DumbKey<V>>(); clear() { this....
} return -1; } } class DumbKey<V> { constructor(public key: any, public value: V) {} }
{ return i; }
conditional_block
harmonic.rs
//! Provides functions for calculating //! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number) //! numbers use crate::consts; use crate::function::gamma; /// Computes the `t`-th harmonic number /// /// # Remarks /// /// Returns `1` as a special case when `t == 0` pub fn harmonic(t: u64) -> f64 { match t { ...
assert_almost_eq!(super::gen_harmonic(4, 1.0), 2.083333333333333333333, 1e-14); assert_eq!(super::gen_harmonic(4, 3.0), 1.177662037037037037037); assert_eq!(super::gen_harmonic(4, f64::INFINITY), 1.0); assert_eq!(super::gen_harmonic(4, f64::NEG_INFINITY), f64::INFINITY); } }
assert_eq!(super::gen_harmonic(1, f64::NEG_INFINITY), 1.0); assert_eq!(super::gen_harmonic(2, 1.0), 1.5); assert_eq!(super::gen_harmonic(2, 3.0), 1.125); assert_eq!(super::gen_harmonic(2, f64::INFINITY), 1.0); assert_eq!(super::gen_harmonic(2, f64::NEG_INFINITY), f64::INFINITY);
random_line_split
harmonic.rs
//! Provides functions for calculating //! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number) //! numbers use crate::consts; use crate::function::gamma; /// Computes the `t`-th harmonic number /// /// # Remarks /// /// Returns `1` as a special case when `t == 0` pub fn harmonic(t: u64) -> f64 { match t { ...
() { assert_eq!(super::gen_harmonic(0, 0.0), 1.0); assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0); assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0); assert_eq!(super::gen_harmonic(1, 0.0), 1.0); assert_eq!(super::gen_harmonic(1, f64::INFINITY), 1.0); ass...
test_gen_harmonic
identifier_name
harmonic.rs
//! Provides functions for calculating //! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number) //! numbers use crate::consts; use crate::function::gamma; /// Computes the `t`-th harmonic number /// /// # Remarks /// /// Returns `1` as a special case when `t == 0` pub fn harmonic(t: u64) -> f64 { match t { ...
#[test] fn test_gen_harmonic() { assert_eq!(super::gen_harmonic(0, 0.0), 1.0); assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0); assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0); assert_eq!(super::gen_harmonic(1, 0.0), 1.0); assert_eq!(super::gen_harmoni...
{ assert_eq!(super::harmonic(0), 1.0); assert_almost_eq!(super::harmonic(1), 1.0, 1e-14); assert_almost_eq!(super::harmonic(2), 1.5, 1e-14); assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14); assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14...
identifier_body
predict.py
import cv2 import numpy from PIL import Image import numpy as np import os from matplotlib import pyplot as plt bin_n = 16 # Number of bins def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/...
(path): pre_out='' print type(pre_out) training_set = [] test_set=[] color_test_set=[] training_labels=[] ###### SVM training ######################## svm = cv2.SVM() svm.load('hog_svm_data1.dat') ###### Now testing HOG ######################## ...
predict_class
identifier_name
predict.py
import cv2 import numpy from PIL import Image import numpy as np import os from matplotlib import pyplot as plt bin_n = 16 # Number of bins def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/...
arr= np.array(img200) flat_arr= arr.ravel() color_test_set.append(flat_arr) testData = np.float32(color_test_set) result = svm1.predict(testData) if result==1: pre_out+=' and '+ 'It has Red Shade' elif result==2: pre_out+=' and '+ 'It has Green Shade' elif resu...
crop_img = res[50:150, 100:200] cv2.imwrite("d:/Emmanu/project-data/color-test.jpg", crop_img) img = Image.open('d:/Emmanu/project-data/color-test.jpg') img200=img.convert('RGBA')
random_line_split
predict.py
import cv2 import numpy from PIL import Image import numpy as np import os from matplotlib import pyplot as plt bin_n = 16 # Number of bins def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/...
def main(): print predict_shape('d:/Emmanu/project-data/tes.jpg') if __name__ == '__main__':main()
training_set = [] test_set=[] color_test_set=[] training_labels=[] result_list=[] ###### Now testing Color ######################## svm1 = cv2.SVM() svm1.load('color_svm_data.dat') img = cv2.imread(path) res=cv2.resize(img,(400,300)) crop_img = res[50:150, ...
identifier_body
predict.py
import cv2 import numpy from PIL import Image import numpy as np import os from matplotlib import pyplot as plt bin_n = 16 # Number of bins def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/...
return pre_out def predict_shape(path,val): training_set = [] test_set=[] test_set1=[] color_test_set=[] training_labels=[] result_list=[] ###### SVM training ######################## svm = cv2.SVM() svm.load('hog_svm_data1.dat') svm1 = cv2.SVM() ...
pre_out+=' and '+ 'It has white Shade'
conditional_block
footer.js
/* *Chris Samuel * ksamuel.chris@icloud.com * * October 5, 2015 * * Filename : Footer.js * * */ import React from 'react'; import {Link} from 'react-router'; import FooterStore from '../stores/FooterStore' import FooterActions from '../actions/FooterActions'; class Footer extends React.Component { constructor(...
} export default Footer;
); }
random_line_split
footer.js
/* *Chris Samuel * ksamuel.chris@icloud.com * * October 5, 2015 * * Filename : Footer.js * * */ import React from 'react'; import {Link} from 'react-router'; import FooterStore from '../stores/FooterStore' import FooterActions from '../actions/FooterActions'; class Footer extends React.Component { constructor(...
render() { let leaderboardCharacters = this.state.characters.map((character) => { return ( <li key={character.characterId}> <Link to={'/characters/' + character.characterId}> <img className='thumb-md' src={'http://image.eveonline.com/...
{ this.setState(state); }
identifier_body
footer.js
/* *Chris Samuel * ksamuel.chris@icloud.com * * October 5, 2015 * * Filename : Footer.js * * */ import React from 'react'; import {Link} from 'react-router'; import FooterStore from '../stores/FooterStore' import FooterActions from '../actions/FooterActions'; class Footer extends React.Component { constructor(...
(state) { this.setState(state); } render() { let leaderboardCharacters = this.state.characters.map((character) => { return ( <li key={character.characterId}> <Link to={'/characters/' + character.characterId}> <img className...
onChange
identifier_name
env_utils.py
# 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/. """Various utility functions used by this plugin""" import subprocess from os import environ, devnull from os.path impor...
else: raise err return stdout
raise NodeNotFoundError(err, node_path)
conditional_block
env_utils.py
# 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/. """Various utility functions used by this plugin""" import subprocess from os import environ, devnull from os.path impor...
"""Runs a command in a shell and returns the output""" popen_args = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "env": environ, } if PLATFORM == "windows": startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW ...
node = get_pref("node_path").get(PLATFORM) return expanduser(node) def run_command(args):
random_line_split
env_utils.py
# 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/. """Various utility functions used by this plugin""" import subprocess from os import environ, devnull from os.path impor...
def run_command(args): """Runs a command in a shell and returns the output""" popen_args = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "env": environ, } if PLATFORM == "windows": startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subproc...
"""Gets the node.js path specified in this plugin's settings file""" node = get_pref("node_path").get(PLATFORM) return expanduser(node)
identifier_body
env_utils.py
# 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/. """Various utility functions used by this plugin""" import subprocess from os import environ, devnull from os.path impor...
(OSError): def __init__(self, original_exception, node_path): msg = "Node.js was not found in the default path" OSError.__init__(self, msg + (": %s" % original_exception)) self.node_path = node_path class NodeRuntimeError(RuntimeError): def __init__(self, stdout, stderr): msg =...
NodeNotFoundError
identifier_name
epoll.rs
use {Errno, Result}; use libc::{self, c_int}; use std::os::unix::io::RawFd; use std::ptr; use std::mem; use ::Error; libc_bitflags!( pub flags EpollFlags: libc::c_int { EPOLLIN, EPOLLPRI, EPOLLOUT, EPOLLRDNORM, EPOLLRDBAND, EPOLLWRNORM, EPOLLWRBAND, E...
{ event: libc::epoll_event, } impl EpollEvent { pub fn new(events: EpollFlags, data: u64) -> Self { EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } } } pub fn empty() -> Self { unsafe { mem::zeroed::<EpollEvent>() } } pub fn events(&self) -> ...
EpollEvent
identifier_name
epoll.rs
use {Errno, Result}; use libc::{self, c_int}; use std::os::unix::io::RawFd; use std::ptr; use std::mem; use ::Error; libc_bitflags!( pub flags EpollFlags: libc::c_int { EPOLLIN, EPOLLPRI, EPOLLOUT, EPOLLRDNORM, EPOLLRDBAND, EPOLLWRNORM, EPOLLWRBAND, E...
} impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> { #[inline] fn into(self) -> &'a mut EpollEvent { match self { Some(epoll_event) => epoll_event, None => unsafe { &mut *ptr::null_mut::<EpollEvent>() } } } } #[inline] pub fn epoll_create() -> Resul...
{ self.event.u64 }
identifier_body
epoll.rs
use {Errno, Result}; use libc::{self, c_int}; use std::os::unix::io::RawFd; use std::ptr; use std::mem; use ::Error; libc_bitflags!( pub flags EpollFlags: libc::c_int { EPOLLIN, EPOLLPRI, EPOLLOUT, EPOLLRDNORM, EPOLLRDBAND, EPOLLWRNORM, EPOLLWRBAND, E...
} else { let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) }; Errno::result(res).map(drop) } } #[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { libc::epoll_wait(epfd, events.as_mut_...
{ let event: &mut EpollEvent = event.into(); if event as *const EpollEvent == ptr::null() && op != EpollOp::EpollCtlDel { Err(Error::Sys(Errno::EINVAL))
random_line_split
flask_app.py
#-*- coding: utf-8 -*- # A very simple Flask Hello World app for you to get started with... from flask import Flask, render_template, redirect, url_for from forms import TestForm app = Flask(__name__, template_folder='/home/dremdem/mysite/templates') app.secret_key = 's3cr3t' class NobodyCare(object): def __in...
не запускали!' form = TestForm() if form.validate_on_submit(): t1 = form.test1.data return render_template('test.html', form=form, t1=t1) @app.route('/') def hello_world(): return render_template('hello.html', a='100')
Еще
identifier_name
flask_app.py
#-*- coding: utf-8 -*- # A very simple Flask Hello World app for you to get started with... from flask import Flask, render_template, redirect, url_for from forms import TestForm app = Flask(__name__, template_folder='/home/dremdem/mysite/templates') app.secret_key = 's3cr3t' class NobodyCare(object): def __in...
.html', form=form, t1=t1) @app.route('/') def hello_world(): return render_template('hello.html', a='100')
ender_template('test
conditional_block
flask_app.py
#-*- coding: utf-8 -*- # A very simple Flask Hello World app for you to get started with... from flask import Flask, render_template, redirect, url_for from forms import TestForm app = Flask(__name__, template_folder='/home/dremdem/mysite/templates') app.secret_key = 's3cr3t' class NobodyCare(object): def __in...
self.people = [u'Иванов', u'Петров', u'Сидоров'] @app.route('/test', methods=['GET', 'POST']) def test(): t1 = u'Еще не запускали!' form = TestForm() if form.validate_on_submit(): t1 = form.test1.data return render_template('test.html', form=form, t1=t1) @app.route('/') def hello_wo...
self.just_b = 'BBBBBBBBB' self.just_123 = '123'
random_line_split
flask_app.py
#-*- coding: utf-8 -*- # A very simple Flask Hello World app for you to get started with... from flask import Flask, render_template, redirect, url_for from forms import TestForm app = Flask(__name__, template_folder='/home/dremdem/mysite/templates') app.secret_key = 's3cr3t' class NobodyCare(object): def __in...
est', methods=['GET', 'POST']) def test(): t1 = u'Еще не запускали!' form = TestForm() if form.validate_on_submit(): t1 = form.test1.data return render_template('test.html', form=form, t1=t1) @app.route('/') def hello_world(): return render_template('hello.html', a='100')
self.just_a = 'AAAAAAAAAA' self.just_b = 'BBBBBBBBB' self.just_123 = '123' self.people = [u'Иванов', u'Петров', u'Сидоров'] @app.route('/t
identifier_body
index.ts
import * as fs from "fs"; import { DirectoryReader } from "../directory-reader"; import { Callback, Options, Stats } from "../types-public"; import { asyncForEach as forEach } from "./for-each"; const asyncFacade = { fs, forEach }; /** * A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` fu...
{ if (typeof options === "function") { callback = options; options = undefined; } let promise = new Promise<T[]>((resolve, reject) => { let results: T[] = []; let reader = new DirectoryReader(dir, options as Options, asyncFacade); let stream = reader.stream; stream.on("error", (err: Erro...
identifier_body
index.ts
import * as fs from "fs"; import { DirectoryReader } from "../directory-reader"; import { Callback, Options, Stats } from "../types-public"; import { asyncForEach as forEach } from "./for-each"; const asyncFacade = { fs, forEach }; /** * A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` fu...
export function readdirAsync(dir: string, options: Options & { stats: true }, callback: Callback<Stats[]>): void; /** * Asynchronous `readdir()` that returns its results via a Promise. */ export function readdirAsync(dir: string, options?: Options & { stats?: false }): Promise<string[]>; /** * Asynchronous `readdi...
*/
random_line_split
index.ts
import * as fs from "fs"; import { DirectoryReader } from "../directory-reader"; import { Callback, Options, Stats } from "../types-public"; import { asyncForEach as forEach } from "./for-each"; const asyncFacade = { fs, forEach }; /** * A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` fu...
<T>(dir: string, options: Options | Callback<T[]> | undefined, callback?: Callback<T[]>): Promise<T[]> | void { if (typeof options === "function") { callback = options; options = undefined; } let promise = new Promise<T[]>((resolve, reject) => { let results: T[] = []; let reader = new DirectoryRe...
readdirAsync
identifier_name
index.ts
import * as fs from "fs"; import { DirectoryReader } from "../directory-reader"; import { Callback, Options, Stats } from "../types-public"; import { asyncForEach as forEach } from "./for-each"; const asyncFacade = { fs, forEach }; /** * A backward-compatible drop-in replacement for Node's built-in `fs.readdir()` fu...
}
{ return promise; }
conditional_block
switch.py
"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure s...
@property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session...
random_line_split
switch.py
"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure s...
(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._devi...
turn_on
identifier_name
switch.py
"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure s...
@property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ...
"""Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label )
identifier_body
switch.py
"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure s...
hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplu...
return False
conditional_block
marching_triangles_performance.rs
extern crate isosurface; extern crate ndarray; use ndarray::Array; use isosurface::marching_triangles; fn
() { let n = 256; let xs = Array::linspace(-0.5f64, 0.5, n); let ys = Array::linspace(-0.5, 0.5, n); let dim = (xs.len(), ys.len()); let u = { let mut u = Array::from_elem(dim, 0.); for ((i, j), u) in u.indexed_iter_mut() { let (x, y) = (xs[i], ys[j]); *u =...
main
identifier_name
marching_triangles_performance.rs
extern crate isosurface; extern crate ndarray; use ndarray::Array; use isosurface::marching_triangles; fn main()
{ let n = 256; let xs = Array::linspace(-0.5f64, 0.5, n); let ys = Array::linspace(-0.5, 0.5, n); let dim = (xs.len(), ys.len()); let u = { let mut u = Array::from_elem(dim, 0.); for ((i, j), u) in u.indexed_iter_mut() { let (x, y) = (xs[i], ys[j]); *u = (x...
identifier_body
marching_triangles_performance.rs
extern crate isosurface; extern crate ndarray; use ndarray::Array; use isosurface::marching_triangles; fn main() { let n = 256; let xs = Array::linspace(-0.5f64, 0.5, n); let ys = Array::linspace(-0.5, 0.5, n);
let u = { let mut u = Array::from_elem(dim, 0.); for ((i, j), u) in u.indexed_iter_mut() { let (x, y) = (xs[i], ys[j]); *u = (x * x + y * y).sqrt() - 0.4; } u }; let mut m = 0; for _ in 0..1000 { let verts = marching_triangles(u.as_slice(...
let dim = (xs.len(), ys.len());
random_line_split
admin.py
# -*- coding: utf-8 -*- # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> # 2015 by Pablo Martín <goinnn@gmail.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundatio...
admin.ModelAdmin): pass admin.site.register(UnusualModel, UnusualModelAdmin)
esourceAdmin(
identifier_name
admin.py
# -*- coding: utf-8 -*- # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> # 2015 by Pablo Martín <goinnn@gmail.com>
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public ...
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
random_line_split
admin.py
# -*- coding: utf-8 -*- # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> # 2015 by Pablo Martín <goinnn@gmail.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundatio...
class ResourceAdmin(admin.ModelAdmin): pass admin.site.register(UnusualModel, UnusualModelAdmin)
ass
identifier_body
generic-lifetime-trait-impl.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 ...
() { }
main
identifier_name
generic-lifetime-trait-impl.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 ...
//~ ERROR lifetime } fn main() { }
{ fail!() }
identifier_body
generic-lifetime-trait-impl.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
// except according to those terms. // This code used to produce an ICE on the definition of trait Bar // with the following message: // // Type parameter out of range when substituting in region 'a (root // type=fn(Self) -> 'astr) (space=FnSpace, index=0) // // Regression test for issue #16218. trait Bar<'a> {} tra...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
processSubjects.py
#!/usr/bin/python ## Wrapper For transverse synapse detector workflow## ## This wrapper exists to facilitate workflow level parallelization inside the LONI pipeline until ## it is properly added to the tool. It is important for this step to do workflow level parallelization ## because of the order of processing. ## ...
# Make Output Directory basename=os.path.basename subDir=os.path.join(outputDirectory,basename(subjDirectory)) print "#@@@# " + subDir + " #@@@#" #os.makedirs(subDir)
print "#MPRAGE# " + os.path.abspath(files) + " #MPRAGE#"
conditional_block
processSubjects.py
#!/usr/bin/python ## Wrapper For transverse synapse detector workflow## ## This wrapper exists to facilitate workflow level parallelization inside the LONI pipeline until ## it is properly added to the tool. It is important for this step to do workflow level parallelization ## because of the order of processing. ## ...
# Find File Names os.chdir(subjDirectory) for files in os.listdir("."): if files.endswith(".b"): print "#B# " + os.path.abspath(files) + " #B#" elif files.endswith(".grad"): print "#GRAD# " + os.path.abspath(files) + " #GRAD#" elif files.endswith("DTI.nii"): print "#DTI# " + os.path.abspath(files) + " #DTI#" ...
params = list(argv) subjDirectory = params[1] outputDirectory = params[2]
random_line_split
urlsearchparams.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams...
, Some(USVStringOrURLSearchParams::URLSearchParams(init)) => { // Step 3. *query.list.borrow_mut() = init.list.borrow().clone(); }, None => {} } // Step 4. Ok(query) } pub fn set_list(&self, list: Vec<(String, String)>)...
{ // Step 2. *query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes()) .into_owned().collect(); }
conditional_block
urlsearchparams.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams...
(&self, name: USVString, value: USVString) { { // Step 1. let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; list.retain(|&(ref k, _)| { if index.is_none() { if k == &name.0 { ...
Set
identifier_name
urlsearchparams.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams...
USVString(value) } fn get_key_at_index(&self, n: u32) -> USVString { let key = self.list.borrow()[n as usize].0.clone(); USVString(key) } }
fn get_value_at_index(&self, n: u32) -> USVString { let value = self.list.borrow()[n as usize].1.clone();
random_line_split
urlsearchparams.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams...
} impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { if let Some(url) = self.url.root() { url.set_query_pairs(&self.list.borrow()) } } } impl Iterable for URLSearchParams { type Key = USVString; type Value =...
{ let list = self.list.borrow(); form_urlencoded::Serializer::new(String::new()) .encoding_override(encoding) .extend_pairs(&*list) .finish() }
identifier_body
result.rs
// Copyright 2012-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-MI...
//! Err(e) => return Err(e) //! } //! return file.write_line(format!("rating: {}", info.rating).as_slice()); //! } //! ~~~ //! //! With this: //! //! ~~~ //! use std::io::{File, Open, Write, IoError}; //! //! struct Info { //! name: String, //! age: int, //! rating: int //! } //! //! fn writ...
//! Err(e) => return Err(e) //! } //! match file.write_line(format!("age: {}", info.age).as_slice()) { //! Ok(_) => (),
random_line_split
result.rs
// Copyright 2012-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-MI...
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. /// /// This function can be used for control flow based on result values #[inline] #[unstable = "waiting for unboxed closures"] pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> { match ...
{ match self { Ok(_) => res, Err(e) => Err(e), } }
identifier_body
result.rs
// Copyright 2012-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-MI...
(self) -> Item<T> { Item{opt: self.ok()} } //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// /// Returns `res` if the result is `Ok`, otherwi...
move_iter
identifier_name
tasks.py
from django.utils import translation from django.conf import settings from froide.celery import app as celery_app from froide.foirequest.models import FoiRequest from .models import FoiRequestFollower from .utils import run_batch_update @celery_app.task def
(request_id, update_message, template=None): translation.activate(settings.LANGUAGE_CODE) try: foirequest = FoiRequest.objects.get(id=request_id) except FoiRequest.DoesNotExist: return followers = FoiRequestFollower.objects.filter(request=foirequest, confirmed=True) for follower in ...
update_followers
identifier_name
tasks.py
from django.utils import translation from django.conf import settings from froide.celery import app as celery_app from froide.foirequest.models import FoiRequest from .models import FoiRequestFollower from .utils import run_batch_update @celery_app.task def update_followers(request_id, update_message, template=None...
@celery_app.task def batch_update(): return run_batch_update()
translation.activate(settings.LANGUAGE_CODE) try: foirequest = FoiRequest.objects.get(id=request_id) except FoiRequest.DoesNotExist: return followers = FoiRequestFollower.objects.filter(request=foirequest, confirmed=True) for follower in followers: FoiRequestFollower.objects.sen...
identifier_body
tasks.py
from django.utils import translation from django.conf import settings from froide.celery import app as celery_app from froide.foirequest.models import FoiRequest from .models import FoiRequestFollower from .utils import run_batch_update @celery_app.task def update_followers(request_id, update_message, template=None...
@celery_app.task def batch_update(): return run_batch_update()
FoiRequestFollower.objects.send_update( follower.user or follower.email, [ { "request": foirequest, "unfollow_link": follower.get_unfollow_link(), "events": [update_message], } ], ...
conditional_block
tasks.py
from django.utils import translation from django.conf import settings from froide.celery import app as celery_app from froide.foirequest.models import FoiRequest from .models import FoiRequestFollower from .utils import run_batch_update @celery_app.task def update_followers(request_id, update_message, template=None...
"events": [update_message], } ], batch=False, ) @celery_app.task def batch_update(): return run_batch_update()
random_line_split
0001_setup_extensions.py
from unittest import mock from django.db import connection, migrations try: from django.contrib.postgres.operations import ( BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension, CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension, )...
operations = [ ( BloomExtension() if getattr(connection.features, 'has_bloom_index', False) else mock.Mock() ), BtreeGinExtension(), BtreeGistExtension(), CITextExtension(), # Ensure CreateExtension quotes extension names by creating on...
identifier_body
0001_setup_extensions.py
from unittest import mock from django.db import connection, migrations
) except ImportError: BloomExtension = mock.Mock() BtreeGinExtension = mock.Mock() BtreeGistExtension = mock.Mock() CITextExtension = mock.Mock() CreateExtension = mock.Mock() CryptoExtension = mock.Mock() HStoreExtension = mock.Mock() TrigramExtension = mock.Mock() UnaccentExten...
try: from django.contrib.postgres.operations import ( BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension, CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension,
random_line_split
0001_setup_extensions.py
from unittest import mock from django.db import connection, migrations try: from django.contrib.postgres.operations import ( BloomExtension, BtreeGinExtension, BtreeGistExtension, CITextExtension, CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension, )...
(migrations.Migration): operations = [ ( BloomExtension() if getattr(connection.features, 'has_bloom_index', False) else mock.Mock() ), BtreeGinExtension(), BtreeGistExtension(), CITextExtension(), # Ensure CreateExtension quotes e...
Migration
identifier_name
delete_group_device.py
# # Delete a device from a group # Copyright © 2020 Dave Hocker # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # See the LICENSE file for more details.
from database.action_group_devices import ActionGroupDevices class DeleteActionGroupDevice(ServerCommand): """ Command handler for assigning a device to a group """ def Execute(self, request): device_id = request["args"]["device-id"] group_id = request["args"]["group-id"] agd ...
# from commands.ServerCommand import ServerCommand
random_line_split
delete_group_device.py
# # Delete a device from a group # Copyright © 2020 Dave Hocker # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # See the LICENSE file for more details. # from co...
self, request): device_id = request["args"]["device-id"] group_id = request["args"]["group-id"] agd = ActionGroupDevices() result = agd.delete_device(group_id, device_id) # Generate a successful response r = self.CreateResponse(request["request"]) # The result ...
xecute(
identifier_name
delete_group_device.py
# # Delete a device from a group # Copyright © 2020 Dave Hocker # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # See the LICENSE file for more details. # from co...
evice_id = request["args"]["device-id"] group_id = request["args"]["group-id"] agd = ActionGroupDevices() result = agd.delete_device(group_id, device_id) # Generate a successful response r = self.CreateResponse(request["request"]) # The result is the number of devices ...
identifier_body
delete_group_device.py
# # Delete a device from a group # Copyright © 2020 Dave Hocker # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # See the LICENSE file for more details. # from co...
else: # Probably invalid device type r['result-code'] = 1 r['error'] = 1 r['message'] = "Failure" return r
['result-code'] = 0 r['group-id'] = group_id r['device_id'] = device_id r['message'] = "Success"
conditional_block
eventMinHeight.ts
import { CalendarWrapper } from '../lib/wrappers/CalendarWrapper' describe('eventMinHeight', () => { pushOptions({ initialView: 'timeGridWeek', initialDate: '2017-08-10', events: [ { start: '2017-08-10T10:30:00', end: '2017-08-10T10:31:00' }, ], }) it('has a non-zero default', () => { ...
expect(eventEl.offsetHeight).toBeGreaterThan(5) }) it('can be set and rendered', () => { let calendar = initCalendar({ eventMinHeight: 40, }) let eventEl = new CalendarWrapper(calendar).getFirstEventEl() expect(eventEl.offsetHeight).toBeGreaterThanOrEqual(39) }) it('will ignore tempo...
random_line_split
cpp_box.rs
use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection}; use crate::vector_ops::{Data, DataMut, Size}; use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast}; use std::ops::Deref; use std::{fmt, mem, ptr, slice}; /// Objects that can be deleted using C++'s `delete` opera...
() { let value1 = Rc::new(RefCell::new(10)); let object1 = Struct1 { value: value1.clone(), }; assert!(*value1.borrow() == 10); unsafe { CppBox::new(Ptr::from_raw(&object1)); } assert!(*value1.borrow() == 42); } }
test_drop_calls_deleter
identifier_name
cpp_box.rs
use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection}; use crate::vector_ops::{Data, DataMut, Size}; use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast}; use std::ops::Deref; use std::{fmt, mem, ptr, slice}; /// Objects that can be deleted using C++'s `delete` opera...
/// ensure that the object will be deleted at some point. pub fn into_raw_ptr(self) -> *mut T { let ptr = self.0.as_ptr(); mem::forget(self); ptr } /// Destroys the box without deleting the object and returns a pointer to the content. /// The caller of the function becomes t...
/// Destroys the box without deleting the object and returns a raw pointer to the content. /// The caller of the function becomes the owner of the object and should
random_line_split
cpp_box.rs
use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection}; use crate::vector_ops::{Data, DataMut, Size}; use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast}; use std::ops::Deref; use std::{fmt, mem, ptr, slice}; /// Objects that can be deleted using C++'s `delete` opera...
/// Returns a reference to the value. /// /// ### Safety /// /// `self` must be valid. /// The content must not be read or modified through other ways while the returned reference /// exists.See type level documentation. pub unsafe fn as_raw_ref<'a>(&self) -> &'a T { &*self.0.a...
{ Ref::from_raw_non_null(self.0) }
identifier_body
works_layout.ts
import styled from 'styled-components' import type { TMetric } from '@/spec' import css from '@/utils/css' import { theme } from '@/utils/themes' // import { WIDTH } from '@/utils/css/metric' import Img from '@/Img' export const Main = styled.div<{ metric: TMetric }>` ${({ metric }) => css.fitContentWidth(metric)};...
` export const TabsWrapper = styled.div` position: absolute; top: 3px; left: -5px; ` export const AuthorName = styled.div` color: ${theme('thread.articleDigest')}; font-size: 14px; `
border-bottom: 1px solid; border-bottom-color: #004251; width: 100%;
random_line_split
main.py
# coding=utf-8 # Copyright 2021 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 agreed ...
_TABLE_ID_ITEMS = 'items' _QUERY_FILEPATH_FOR_UPSERT = 'queries/items_to_upsert.sql' _QUERY_FILEPATH_FOR_DELETE = 'queries/items_to_delete.sql' _QUERY_FILEPATH_FOR_PREVENT_EXPIRING = 'queries/items_to_prevent_expiring.sql' _MAILER_TOPIC_NAME = 'mailer-trigger' _API_METHOD_INSERT = 'insert' _API_METHOD_DELETE = 'delete...
_DATASET_ID_FEED_DATA = 'feed_data'
random_line_split
main.py
# coding=utf-8 # Copyright 2021 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 agreed ...
() -> None: """Deletes EOF.lock file to allow the next run.""" gcs_client = storage_client.StorageClient.from_service_account_json( _SERVICE_ACCOUNT, _LOCK_BUCKET) gcs_client.delete_eof_lock() def _trigger_mailer_for_nothing_processed() -> None: """Sends a completion email showing 0 upsert/deletion/expi...
_delete_eof_lock
identifier_name
main.py
# coding=utf-8 # Copyright 2021 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 agreed ...
if __name__ == '__main__': # This is used when running locally. Gunicorn is used to run the # application on Google App Engine. See entrypoint in app.yaml. app.run(host='127.0.0.1', port=8080, debug=True)
"""Sends a completion email showing 0 upsert/deletion/expiring calls (sent when no diff).""" pubsub_publisher = pubsub_client.PubSubClient.from_service_account_json( _SERVICE_ACCOUNT) operation_counts_dict = { operation: operation_counts.OperationCounts(operation, 0, 0, 0) for operation in OPERATI...
identifier_body
main.py
# coding=utf-8 # Copyright 2021 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 agreed ...
app.run(host='127.0.0.1', port=8080, debug=True)
conditional_block
collector_crimeserver.py
# -*- coding: utf-8 -*- import json import logging import sys from intelmq.lib.bot import Bot from intelmq.lib.message import Report from sdk.blueliv_api import BluelivAPI class BluelivCrimeserverCollectorBot(Bot): def process(self): self.logger.info("Downloading report through API") http_proxy ...
bot = BluelivCrimeserverCollectorBot(sys.argv[1]) bot.start()
conditional_block
collector_crimeserver.py
# -*- coding: utf-8 -*- import json import logging import sys from intelmq.lib.bot import Bot from intelmq.lib.message import Report from sdk.blueliv_api import BluelivAPI class BluelivCrimeserverCollectorBot(Bot): def
(self): self.logger.info("Downloading report through API") http_proxy = getattr(self.parameters, 'http_proxy', None) https_proxy = getattr(self.parameters, 'http_ssl_proxy', None) proxy = None if http_proxy and https_proxy: proxy = {'http': http_proxy, ...
process
identifier_name
collector_crimeserver.py
# -*- coding: utf-8 -*- import json import logging import sys from intelmq.lib.bot import Bot from intelmq.lib.message import Report from sdk.blueliv_api import BluelivAPI class BluelivCrimeserverCollectorBot(Bot): def process(self):
if __name__ == "__main__": bot = BluelivCrimeserverCollectorBot(sys.argv[1]) bot.start()
self.logger.info("Downloading report through API") http_proxy = getattr(self.parameters, 'http_proxy', None) https_proxy = getattr(self.parameters, 'http_ssl_proxy', None) proxy = None if http_proxy and https_proxy: proxy = {'http': http_proxy, 'https': h...
identifier_body
collector_crimeserver.py
# -*- coding: utf-8 -*- import json import logging import sys from intelmq.lib.bot import Bot from intelmq.lib.message import Report from sdk.blueliv_api import BluelivAPI class BluelivCrimeserverCollectorBot(Bot): def process(self): self.logger.info("Downloading report through API") http_proxy ...
self.logger.info("Report downloaded.") report = Report() report.add("raw", json.dumps([item for item in response.items])) report.add("feed.name", self.parameters.feed) report.add("feed.accuracy", self.parameters.accuracy) self.send_message(report) if __name__ == "__mai...
proxy=proxy) response = api.crime_servers.online()
random_line_split
pos_receipt.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from openerp.osv import osv from openerp.report import report_sxw def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) ...
return dsum def _get_journal_amt(self, order_id): data={} sql = """ select aj.name,absl.amount as amt from account_bank_statement as abs LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id LEFT JOIN account_journal as ...
if line[0] != 0: dsum = dsum +(line[2] * (line[0]*line[1]/100))
conditional_block
pos_receipt.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from openerp.osv import osv from openerp.report import report_sxw def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) ...
_name = 'report.point_of_sale.report_receipt' _inherit = 'report.abstract_report' _template = 'point_of_sale.report_receipt' _wrapped_report_class = order
identifier_body
pos_receipt.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from openerp.osv import osv from openerp.report import report_sxw def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) ...
(osv.AbstractModel): _name = 'report.point_of_sale.report_receipt' _inherit = 'report.abstract_report' _template = 'point_of_sale.report_receipt' _wrapped_report_class = order
report_order_receipt
identifier_name
pos_receipt.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from openerp.osv import osv from openerp.report import report_sxw
def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) class order(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(order, self).__init__(cr, uid, name, context=context) user = self.poo...
random_line_split
index.js
var Promise = require('rsvp').Promise; var merge = require('ember-cli-lodash-subset').merge; var inflection = require('inflection'); module.exports = { description: 'Generates a model and route.', install: function(options) { return this._process('install', options); }, uninstall: function(option...
return testBlueprint[type](options); }); }, _findBlueprintBaseClass: function(cls) { if (cls.constructor && cls.constructor.name === 'Blueprint') { return cls.constructor; } if (cls._super) { return this._findBlueprintBaseClass(cls._super); } return null; }, _...
{ testBlueprint.locals = function(options) { return mainBlueprint.locals(options); }; }
conditional_block
index.js
var Promise = require('rsvp').Promise; var merge = require('ember-cli-lodash-subset').merge; var inflection = require('inflection'); module.exports = { description: 'Generates a model and route.', install: function(options) { return this._process('install', options); }, uninstall: function(option...
ignoreMissing: true }); if (!testBlueprint) { return; } var Blueprint = that._findBlueprintBaseClass(testBlueprint); if (Blueprint && testBlueprint.locals === Blueprint.prototype.locals) { testBlueprint.locals = function(options) { return mainBlueprint.l...
project: this.project,
random_line_split
test_event_name_code_year_id.py
# Copyright 2021 Alfredo de la Fuente - Avanzosc S.L.
@tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def setUpClass(cls): super(TestNameCodeYearId, cls).setUpClass() cls.event_obj = cls.env['event.event'] cls.skill_type_lang = cls.env.ref('hr_skills.hr_skill_type_lang') cls.skil...
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged
random_line_split
test_event_name_code_year_id.py
# Copyright 2021 Alfredo de la Fuente - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged @tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def setUpClass(cls): sup...
vals = {'name': 'User for event lang level', 'date_begin': '2025-01-06 08:00:00', 'date_end': '2025-01-15 10:00:00', 'lang_id': self.skill_spanish.id} event = self.event_obj.create(vals) name = 'SP-{}-2025'.format(event.id) self.assertEqual(event.n...
identifier_body
test_event_name_code_year_id.py
# Copyright 2021 Alfredo de la Fuente - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged @tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def setUpClass(cls): sup...
(self): vals = {'name': 'User for event lang level', 'date_begin': '2025-01-06 08:00:00', 'date_end': '2025-01-15 10:00:00', 'lang_id': self.skill_spanish.id} event = self.event_obj.create(vals) name = 'SP-{}-2025'.format(event.id) self.ass...
test_event_name_code_year_id
identifier_name
opt_vec.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 ...
impl<T:Copy> OptVec<T> { fn prepend(&self, t: T) -> OptVec<T> { let mut v0 = ~[t]; match *self { Empty => {} Vec(ref v1) => { v0.push_all(*v1); } } return Vec(v0); } fn push_all<I: BaseIter<T>>(&mut self, from: &I) { for from.each |e| { ...
{ match v { Empty => ~[], Vec(v) => v } }
identifier_body
opt_vec.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 ...
Vec(v) => v } } impl<T:Copy> OptVec<T> { fn prepend(&self, t: T) -> OptVec<T> { let mut v0 = ~[t]; match *self { Empty => {} Vec(ref v1) => { v0.push_all(*v1); } } return Vec(v0); } fn push_all<I: BaseIter<T>>(&mut self, from: &I) { ...
random_line_split
opt_vec.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 ...
<'a>(&'a self, i: uint) -> &'a T { match *self { Empty => fail!("Invalid index %u", i), Vec(ref v) => &v[i] } } fn is_empty(&self) -> bool { self.len() == 0 } fn len(&self) -> uint { match *self { Empty => 0, Vec(ref v) =>...
get
identifier_name
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::FontHandleMethods; use platform::font::FontHandle; use platform::font_context::FontContextHandle; use pl...
(&self, f: &mut Formatter) -> Result<(), Error> { self.identifier.fmt(f) } } /// Holds all of the template information for a font that /// is common, regardless of the number of instances of /// this font handle per thread. impl FontTemplate { pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) ...
fmt
identifier_name
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::FontHandleMethods; use platform::font::FontHandle; use platform::font_context::FontContextHandle; use pl...
} /// This describes all the information needed to create /// font instance handles. It contains a unique /// FontTemplateData structure that is platform specific. pub struct FontTemplate { identifier: Atom, descriptor: Option<FontTemplateDescriptor>, weak_ref: Option<Weak<FontTemplateData>>, // GWTOD...
{ self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic }
identifier_body
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::FontHandleMethods; use platform::font::FontHandle; use platform::font_context::FontContextHandle; use pl...
#[inline] fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 { if self.stretch != other.stretch || self.italic != other.italic { // A value higher than all weights. return 1000 } ((self.weight as i16) - (other.weight as i16)).abs() as u32 } } impl...
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must /// be commutative (distance(A, B) == distance(B, A)).
random_line_split
mootools-more-1.4.0.1.js
// MooTools: the javascript framework. // Load this file's selection again by visiting: http://mootools.net/more/a48fe2353ed8fa38be320f8557db4ff2 // Or build this file again with packager using: packager build More/Class.Binds More/Element.Measure /* --- copyrights: - [MooTools](http://mootools.net) license...
b(d.styles,d.planes).each(function(h){g[h]=this.getStyle(h).toInt(); },this);Object.each(d.planes,function(i,h){var k=h.capitalize(),j=this.getStyle(h);if(j=="auto"&&!f){f=this.getDimensions();}j=g[h]=(j=="auto")?f[h]:j.toInt(); e["total"+k]=j;i.each(function(m){var l=c(m,g);e["computed"+m.capitalize()]=l;e["total"+k...
{if(d.mode=="horizontal"){delete e.height;delete d.planes.height;}}
conditional_block
mootools-more-1.4.0.1.js
// MooTools: the javascript framework. // Load this file's selection again by visiting: http://mootools.net/more/a48fe2353ed8fa38be320f8557db4ff2 // Or build this file again with packager using: packager build More/Class.Binds More/Element.Measure /* --- copyrights: - [MooTools](http://mootools.net) license...
},this);Object.each(d.planes,function(i,h){var k=h.capitalize(),j=this.getStyle(h);if(j=="auto"&&!f){f=this.getDimensions();}j=g[h]=(j=="auto")?f[h]:j.toInt(); e["total"+k]=j;i.each(function(m){var l=c(m,g);e["computed"+m.capitalize()]=l;e["total"+k]+=l;});},this);return Object.append(e,g);}});})();
},getComputedSize:function(d){d=Object.merge({styles:["padding","border"],planes:{height:["top","bottom"],width:["left","right"]},mode:"both"},d);var g={},e={width:0,height:0},f; if(d.mode=="vertical"){delete e.width;delete d.planes.width;}else{if(d.mode=="horizontal"){delete e.height;delete d.planes.height;}}b(d.styl...
random_line_split