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
import_visits.py
import csv, os from Products.CMFCore.utils import getToolByName def get_folder(self, type, name): folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0] return folder_brains.getObject() def create_object_in_directory(self, container, type): id = container.generateUniqueId(type) conta...
for row in reader: if not row: continue header = ['School', 'Student Name', 'Instrument', 'Student Email', 'Student Phone', 'Student Address', 'Student City', 'Student Zip', 'Contact Name', 'Contact Title', 'Contact Phone', 'Contact Email', 'Is Contact Alumni', 'Date'] scho...
def import_visits(self): reader = csv.reader(self.REQUEST.get('csv-file-contents').split(os.linesep), delimiter="\t")
random_line_split
import_visits.py
import csv, os from Products.CMFCore.utils import getToolByName def get_folder(self, type, name): folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0] return folder_brains.getObject() def create_object_in_directory(self, container, type): id = container.generateUniqueId(type) conta...
def set_reference(self, object, visit): existing_visits = object.getVisits() if visit not in existing_visits: existing_visits.append(visit) object.setVisits(existing_visits) def import_visits(self): reader = csv.reader(self.REQUEST.get('csv-file-contents').split(os.linesep), delimiter="\...
return create_object_in_directory(self, folder, type)
conditional_block
import_visits.py
import csv, os from Products.CMFCore.utils import getToolByName def get_folder(self, type, name): folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0] return folder_brains.getObject() def create_object_in_directory(self, container, type): id = container.generateUniqueId(type) conta...
reader = csv.reader(self.REQUEST.get('csv-file-contents').split(os.linesep), delimiter="\t") for row in reader: if not row: continue header = ['School', 'Student Name', 'Instrument', 'Student Email', 'Student Phone', 'Student Address', 'Student City', 'Student Zip', 'Contact Name', 'Co...
identifier_body
ffi.rs
//! Useful tools for C FFI use std::ffi::CString; use std::os::raw::{c_char, c_int}; use std::ptr; /// Call a main-like function with an argument vector /// /// # Safety /// /// Safety depends on the safety of the target FFI function. pub unsafe fn run_with_args<S: AsRef<str>, Argv: IntoIterator<Item = S>>( func:...
} c_char_buffer.push(ptr::null_mut()); let c_argv = c_char_buffer.as_mut_ptr(); // 4. Now call the function func(argc, c_argv) as i32 }
c_char_buffer.push(cstring.as_bytes_with_nul().as_ptr() as *mut c_char);
random_line_split
ffi.rs
//! Useful tools for C FFI use std::ffi::CString; use std::os::raw::{c_char, c_int}; use std::ptr; /// Call a main-like function with an argument vector /// /// # Safety /// /// Safety depends on the safety of the target FFI function. pub unsafe fn run_with_args<S: AsRef<str>, Argv: IntoIterator<Item = S>>( func:...
{ // 1. First clone the string values into safe storage. let cstring_buffer: Vec<_> = args .into_iter() .map(|arg| CString::new(arg.as_ref()).expect("String to CString conversion failed")) .collect(); // 2. Total number of args is fixed. let argc = cstring_buffer.len() as c_int;...
identifier_body
ffi.rs
//! Useful tools for C FFI use std::ffi::CString; use std::os::raw::{c_char, c_int}; use std::ptr; /// Call a main-like function with an argument vector /// /// # Safety /// /// Safety depends on the safety of the target FFI function. pub unsafe fn
<S: AsRef<str>, Argv: IntoIterator<Item = S>>( func: unsafe extern "C" fn(c_int, *mut *mut c_char) -> c_int, args: Argv, ) -> i32 { // 1. First clone the string values into safe storage. let cstring_buffer: Vec<_> = args .into_iter() .map(|arg| CString::new(arg.as_ref()).expect("String t...
run_with_args
identifier_name
shorten_path.py
#!/usr/bin/env python import sys import os import re try: path = sys.argv[1] length = int(sys.argv[2]) except: print >>sys.stderr, "Usage: $0 <path> <length>" sys.exit(1) path = re.sub(os.getenv('HOME'), '~', path) while len(path) > length: dirs = path.split("/"); # Find the longest directo...
# Shorten it by one character. if max_index >= 0: dirs[max_index] = dirs[max_index][:max_length-3] + ".." path = "/".join(dirs) # Didn't find anything to shorten. This is as good as it gets. else: break print(path)
max_index = i max_length = len(dirs[i])
conditional_block
shorten_path.py
#!/usr/bin/env python import sys import os import re try: path = sys.argv[1] length = int(sys.argv[2]) except: print >>sys.stderr, "Usage: $0 <path> <length>" sys.exit(1) path = re.sub(os.getenv('HOME'), '~', path) while len(path) > length: dirs = path.split("/"); # Find the longest directo...
else: break print(path)
dirs[max_index] = dirs[max_index][:max_length-3] + ".." path = "/".join(dirs) # Didn't find anything to shorten. This is as good as it gets.
random_line_split
landmarks_file.py
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library 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.0 of the License, or (at...
# Read landmarks position landmarks = np.empty((landmarks_number, 2), dtype=np.float) for i in range(landmarks_number): landmarks[i] = np.array([float(x) for x in f.readline().split()]) return landmarks
f.readline()
conditional_block
landmarks_file.py
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library 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.0 of the License, or (at...
# 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 # License along with this library. import numpy as np def read...
# # This library is distributed in the hope that it will be useful,
random_line_split
landmarks_file.py
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library 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.0 of the License, or (at...
f = open(filename) # Skip first 3 lines for i in range(3): f.readline() # Read landmarks position landmarks = np.empty((landmarks_number, 2), dtype=np.float) for i in range(landmarks_number): landmarks[i] = np.array([float(x) for x in f.readline().split()]) return ...
identifier_body
landmarks_file.py
# ID-Fits # Copyright (c) 2015 Institut National de l'Audiovisuel, INA, All rights reserved. # # This library 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.0 of the License, or (at...
(filename, landmarks_number): f = open(filename) # Skip first 3 lines for i in range(3): f.readline() # Read landmarks position landmarks = np.empty((landmarks_number, 2), dtype=np.float) for i in range(landmarks_number): landmarks[i] = np.array([float(x) for x in f.readline()....
readPtsLandmarkFile
identifier_name
translate_to_glib.rs
use crate::{ analysis::{function_parameters::TransformationType, ref_mode::RefMode}, library::Transfer, }; pub trait TranslateToGlib { fn translate_to_glib(&self) -> String; } impl TranslateToGlib for TransformationType { fn translate_to_glib(&self) -> String { use self::TransformationType::*;...
{ use self::Transfer::*; match transfer { None => { match ref_mode { RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(), RefMode::ByRef => { if explicit_target_type.is_empty() { ("".into(), ".to_...
identifier_body
translate_to_glib.rs
use crate::{ analysis::{function_parameters::TransformationType, ref_mode::RefMode}, library::Transfer, }; pub trait TranslateToGlib { fn translate_to_glib(&self) -> String; } impl TranslateToGlib for TransformationType { fn translate_to_glib(&self) -> String { use self::TransformationType::*;...
format!(".map(|p| p{})", to_glib_extra) } else { to_glib_extra.clone() }; if instance_parameter { format!( "{}self{}{}{}", left, if in_trai...
let (left, right) = to_glib_xxx(transfer, ref_mode, explicit_target_type); let to_glib_extra = if nullable && !to_glib_extra.is_empty() {
random_line_split
translate_to_glib.rs
use crate::{ analysis::{function_parameters::TransformationType, ref_mode::RefMode}, library::Transfer, }; pub trait TranslateToGlib { fn translate_to_glib(&self) -> String; } impl TranslateToGlib for TransformationType { fn translate_to_glib(&self) -> String { use self::TransformationType::*;...
( transfer: Transfer, ref_mode: RefMode, explicit_target_type: &str, ) -> (String, &'static str) { use self::Transfer::*; match transfer { None => { match ref_mode { RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(), RefMode::...
to_glib_xxx
identifier_name
weak.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} #[unsafe_destructor] impl<T> Drop for Strong<T> { fn drop(&mut self) { unsafe { if self.ptr != 0 as *mut RcBox<T> { (*self.ptr).strong -= 1; if (*self.ptr).strong == 0 { read_ptr(self.borrow()); // destroy the contained object ...
{ unsafe { (*self.ptr).weak += 1; Weak { ptr: self.ptr } } }
identifier_body
weak.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } } #[unsafe_destructor] impl<T> Drop for Weak<T> { fn drop(&mut self) { unsafe { if self.ptr != 0 as *mut RcBox<T> { (*self.ptr).weak -= 1; if (*self.ptr).weak == 0 { free(self.ptr as *mut u8) } } ...
{ (*self.ptr).strong += 1; Some(Strong { ptr: self.ptr }) }
conditional_block
weak.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 ...
#[inline] fn deep_clone(&self) -> Strong<T> { Strong::new(self.borrow().deep_clone()) } } impl<T: Eq> Eq for Strong<T> { #[inline(always)] fn eq(&self, other: &Strong<T>) -> bool { *self.borrow() == *other.borrow() } #[inline(always)] fn ne(&self, other: &Strong<T>) -> bool { *self...
} impl<T: DeepClone> DeepClone for Strong<T> {
random_line_split
weak.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, other: &Strong<T>) -> bool { *self.borrow() > *other.borrow() } #[inline(always)] fn ge(&self, other: &Strong<T>) -> bool { *self.borrow() >= *other.borrow() } } #[unsafe_no_drop_flag] pub struct Weak<T> { ptr: *mut RcBox<T> } impl<T> Weak<T> { pub fn upgrade(&self) -> Option<Strong<T>> { ...
gt
identifier_name
service.py
""" System services =============== This module provides low-level tools for managing system services, using the ``service`` command. It supports both `upstart`_ services and traditional SysV-style ``/etc/init.d/`` scripts. .. _upstart: http://upstart.ubuntu.com/ """ from __future__ import with_statement from fabri...
""" Force reload a service. :: import fabtools # Force reload service fabtools.service.force_reload('foo') .. warning:: The service needs to support the ``force-reload`` operation. """ sudo('service %(service)s force-reload' % locals())
identifier_body
service.py
""" System services =============== This module provides low-level tools for managing system services, using the ``service`` command. It supports both `upstart`_ services and traditional SysV-style ``/etc/init.d/`` scripts. .. _upstart: http://upstart.ubuntu.com/ """ from __future__ import with_statement from fabri...
(service): """ Stop a service. :: import fabtools # Stop service if it is running if fabtools.service.is_running('foo'): fabtools.service.stop('foo') """ sudo('service %(service)s stop' % locals()) def restart(service): """ Restart a service. :: ...
stop
identifier_name
service.py
""" System services =============== This module provides low-level tools for managing system services, using the ``service`` command. It supports both `upstart`_ services and traditional SysV-style ``/etc/init.d/`` scripts. .. _upstart: http://upstart.ubuntu.com/ """ from __future__ import with_statement from fabri...
fabtools.service.start('foo') """ sudo('service %(service)s start' % locals()) def stop(service): """ Stop a service. :: import fabtools # Stop service if it is running if fabtools.service.is_running('foo'): fabtools.service.stop('foo') """ ...
if not fabtools.service.is_running('foo'):
random_line_split
import_onnx.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(object): # pylint: disable=too-few-public-methods """A helper class for handling mxnet symbol copying from pb2.GraphProto. Definition: https://github.com/onnx/onnx/blob/master/onnx/onnx.proto """ def __init__(self): self._nodes = {} self._params = {} self._num_input = 0 ...
GraphProto
identifier_name
import_onnx.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def _parse_array(self, tensor_proto): """Grab data in TensorProto and convert to numpy array.""" try: from onnx.numpy_helper import to_array except ImportError: raise ImportError("Onnx and protobuf need to be installed. " + "Instruction...
"""Construct symbol from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol The returned mxnet symbol params : dict A dict of name: nd.array pairs, used as p...
identifier_body
import_onnx.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
else: self._nodes[i.name] = symbol.Variable(name=i.name) # For storing arg and aux params for the graph. auxDict = {} argDict = {} # constructing nodes, nodes are stored as directed acyclic graph # converting NodeProto message for node in g...
self._nodes[i.name] = symbol.Variable(name=i.name, shape=self._params[i.name].shape)
conditional_block
import_onnx.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
if node_name is None: mxnet_sym = new_op(*inputs, **new_attrs) else: mxnet_sym = new_op(name=node_name, *inputs, **new_attrs) return mxnet_sym return op_name def from_onnx(self, graph): """Construct symbol from onnx graph. ...
raise RuntimeError("Unable to map op_name {} to sym".format(op_name))
random_line_split
VProgressLinear.js
import { VFadeTransition, VSlideXTransition } from '~components/transitions' export default { name: 'v-progress-linear', components: { VFadeTransition, VSlideXTransition }, props: { active: { type: Boolean, default: true }, buffer: Boolean, bufferValue: Number, err...
(h) { return h('div', { ref: 'front', class: { 'progress-linear__bar__indeterminate': true, 'progress-linear__bar__indeterminate--active': this.active } }, [ this.genBar(h, 'long'), this.genBar(h, 'short') ]) } }, render (h) { c...
genIndeterminate
identifier_name
VProgressLinear.js
import { VFadeTransition, VSlideXTransition } from '~components/transitions' export default { name: 'v-progress-linear', components: { VFadeTransition, VSlideXTransition }, props: { active: { type: Boolean, default: true }, buffer: Boolean, bufferValue: Number, err...
return styles } }, methods: { genDeterminate (h) { return h('div', { ref: 'front', class: ['progress-linear__bar__determinate', this.colorFront], style: { width: `${this.value}%` } }) }, genBar (h, name) { return h('div', { class: [ ...
{ styles.height = 0 }
conditional_block
VProgressLinear.js
import { VFadeTransition, VSlideXTransition } from '~components/transitions' export default { name: 'v-progress-linear', components: { VFadeTransition, VSlideXTransition }, props: { active: { type: Boolean, default: true },
bufferValue: Number, error: Boolean, height: { type: [Number, String], default: 7 }, indeterminate: Boolean, info: Boolean, secondary: Boolean, success: Boolean, query: Boolean, warning: Boolean, value: { type: [Number, String], default: 0 }, c...
buffer: Boolean,
random_line_split
VProgressLinear.js
import { VFadeTransition, VSlideXTransition } from '~components/transitions' export default { name: 'v-progress-linear', components: { VFadeTransition, VSlideXTransition }, props: { active: { type: Boolean, default: true }, buffer: Boolean, bufferValue: Number, err...
}, render (h) { const fade = h('v-fade-transition', [this.indeterminate && this.genIndeterminate(h)]) const slide = h('v-slide-x-transition', [!this.indeterminate && this.genDeterminate(h)]) const bar = h('div', { class: ['progress-linear__bar', this.colorBack], style: this.styles }, [fade, slide]) ...
{ return h('div', { ref: 'front', class: { 'progress-linear__bar__indeterminate': true, 'progress-linear__bar__indeterminate--active': this.active } }, [ this.genBar(h, 'long'), this.genBar(h, 'short') ]) }
identifier_body
test_context.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 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 writing, software # ...
# All Rights Reserved.
random_line_split
test_context.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apac...
class FilterFactoryTest(test.BaseTestCase): def test_filter_factory(self): global_conf = dict(sentinel=mock.sentinel.global_conf) app = mock.sentinel.app target = 'openstack.common.middleware.context.ContextMiddleware' def check_ctx_middleware(arg_app, arg_conf): sel...
app = mock.Mock() import_class = mock.Mock() options = {'context_class': mock.sentinel.context_class} with mock.patch('openstack.common.importutils.import_class', mock.Mock(return_value=import_class)): ctx_middleware = context.ContextMiddleware(app, options) ...
identifier_body
test_context.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apac...
(self): app = mock.Mock() import_class = mock.Mock() options = {'context_class': mock.sentinel.context_class} with mock.patch('openstack.common.importutils.import_class', mock.Mock(return_value=import_class)): ctx_middleware = context.ContextMiddleware...
test_make_explicit_context
identifier_name
variables_15.js
var searchData= [ ['scroll',['scroll',['../select2_8js.html#a6e3896ca7181e81b7757bfcca39055ec',1,'select2.js']]], ['scrollbardimensions',['scrollBarDimensions',['../select2_8js.html#a30eb565a7710bd54761b6bfbcfd9d3fd',1,'select2.js']]], ['select',['select',['../select2_8js.html#ac07257b5178416a2fbbba7365d2703a6',1...
];
['self',['self',['../select2_8js.html#ab3e74e211b41d329801623ae131d2585',1,'select2.js']]], ['singleselect2',['SingleSelect2',['../select2_8js.html#ab661105ae7b811b84224646465ea5c63',1,'select2.js']]], ['sizer',['sizer',['../select2_8js.html#a9db90058e07b269a04a8990251dab3c4',1,'select2.js']]], ['sn',['sn',['.....
random_line_split
adt-tuple-struct.rs
// Copyright 2017 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 annot_underscore() { let c = 66; SomeStruct::<_>(&c); } fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32>(&c); } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32>(&c); //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c...
random_line_split
adt-tuple-struct.rs
// Copyright 2017 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 annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32>(&c); } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32>(&c); //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c = 66; SomeStruct::<&'a u32>(&c); //~ ERROR } fn annot_reference...
{ let c = 66; SomeStruct::<_>(&c); }
identifier_body
adt-tuple-struct.rs
// Copyright 2017 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 ...
<T>(T); fn no_annot() { let c = 66; SomeStruct(&c); } fn annot_underscore() { let c = 66; SomeStruct::<_>(&c); } fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32>(&c); } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32>(&c); //~ ERROR } f...
SomeStruct
identifier_name
menu.py
# GNU Enterprise Forms - wx 2.6 UI Driver - Menu widget # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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 Foundatio...
elif hasattr(self._gfObject.getParent().uiWidget, '_ui_set_context_menu_'): self._container = PopupMenu(self, self._gfObject.label or '') # table tree and button supports _ui_set_context_menu_() interface self._gfObject.getParent().uiWidget._ui_set_context_menu_(self._container, self._gfObject.name) ...
self._container = Menu(self, self._gfObject.label or '') if isinstance(event.container, (MenuBar, Menu)): event.container.uiAddMenu(self._container)
conditional_block
menu.py
# GNU Enterprise Forms - wx 2.6 UI Driver - Menu widget # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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 Foundatio...
# ============================================================================= # Configuration data # ============================================================================= configuration = { 'baseClass': UIMenu, 'provides' : 'GFMenu', 'container': 1, }
random_line_split
menu.py
# GNU Enterprise Forms - wx 2.6 UI Driver - Menu widget # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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 Foundatio...
# ============================================================================= # Configuration data # ============================================================================= configuration = { 'baseClass': UIMenu, 'provides' : 'GFMenu', 'container': 1, }
""" Creates a new Menu widget. """ if self._gfObject.name == '__main_menu__': if not self._form._features['GUI:MENUBAR:SUPPRESS'] and not self._uiForm.isEmbeded() and self._form.style != 'dialog': assert self._uiForm.menuBar is None # We do not set the menubar using main_window.SetMenuBar() here, ...
identifier_body
menu.py
# GNU Enterprise Forms - wx 2.6 UI Driver - Menu widget # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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 Foundatio...
(UIWidget): """ Implements a menu object. """ # ------------------------------------------------------------------------- # Constructor # ------------------------------------------------------------------------- def __init__(self, event): UIWidget.__init__(self, event) # -----------------------------------...
UIMenu
identifier_name
axis_input_box_group.tsx
import * as React from "react"; import { AxisInputBox } from "./axis_input_box"; import { Row, Col } from "../ui/index"; import { AxisInputBoxGroupProps, AxisInputBoxGroupState } from "./interfaces"; import { isNumber } from "lodash"; import { Vector3 } from "farmbot"; import { t } from "../i18next_wrapper"; /** Coord...
(props: AxisInputBoxGroupProps) { super(props); this.state = {}; } change = (axis: keyof Vector3, val: number) => { this.setState({ [axis]: val }); } get vector() { const { x, y, z } = this.state; const p = this.props.position; const x2 = p.x, y2 = p.y, z2 = p.z; retur...
constructor
identifier_name
axis_input_box_group.tsx
import * as React from "react"; import { AxisInputBox } from "./axis_input_box"; import { Row, Col } from "../ui/index"; import { AxisInputBoxGroupProps, AxisInputBoxGroupState } from "./interfaces"; import { isNumber } from "lodash"; import { Vector3 } from "farmbot"; import { t } from "../i18next_wrapper"; /** Coord...
change = (axis: keyof Vector3, val: number) => { this.setState({ [axis]: val }); } get vector() { const { x, y, z } = this.state; const p = this.props.position; const x2 = p.x, y2 = p.y, z2 = p.z; return { x: isNumber(x) ? x : (x2 || 0), y: isNumber(y) ? y : (y2 || ...
{ super(props); this.state = {}; }
identifier_body
axis_input_box_group.tsx
import * as React from "react"; import { AxisInputBox } from "./axis_input_box"; import { Row, Col } from "../ui/index"; import { AxisInputBoxGroupProps, AxisInputBoxGroupState } from "./interfaces"; import { isNumber } from "lodash"; import { Vector3 } from "farmbot"; import { t } from "../i18next_wrapper"; /** Coord...
get vector() { const { x, y, z } = this.state; const p = this.props.position; const x2 = p.x, y2 = p.y, z2 = p.z; return { x: isNumber(x) ? x : (x2 || 0), y: isNumber(y) ? y : (y2 || 0), z: isNumber(z) ? z : (z2 || 0) }; } clicked = () => { this.props.onCom...
this.setState({ [axis]: val }); }
random_line_split
main.rs
/* --- Day 5: How About a Nice Game of Chess? --- You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies. The eight-character password for the door is generated one character at a time by finding the MD5 hash of some...
} // we got em. 😏 let pass_string : String = pass.iter().map(|c| c.unwrap()).collect(); println!("[PART B] cracked the pass: {:?}", pass_string); } fn main() { const PUZZLE_INPUT : &'static str = "reyedfim"; solve_part_a(PUZZLE_INPUT); solve_part_b(PUZZLE_INPUT); }
break; }
conditional_block
main.rs
/* --- Day 5: How About a Nice Game of Chess? --- You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0). A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the si...
random_line_split
main.rs
/* --- Day 5: How About a Nice Game of Chess? --- You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies. The eight-character password for the door is generated one character at a time by finding the MD5 hash of some...
const PUZZLE_INPUT : &'static str = "reyedfim"; solve_part_a(PUZZLE_INPUT); solve_part_b(PUZZLE_INPUT); }
identifier_body
main.rs
/* --- Day 5: How About a Nice Game of Chess? --- You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies. The eight-character password for the door is generated one character at a time by finding the MD5 hash of some...
const PUZZLE_INPUT : &'static str = "reyedfim"; solve_part_a(PUZZLE_INPUT); solve_part_b(PUZZLE_INPUT); }
{
identifier_name
htmlheadelement.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::codegen::HTMLHeadElementBinding; use dom::bindings::codegen::InheritTypes::HTMLHeadElementDeriv...
}
random_line_split
htmlheadelement.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::codegen::HTMLHeadElementBinding; use dom::bindings::codegen::InheritTypes::HTMLHeadElementDeriv...
{ htmlelement: HTMLElement } impl HTMLHeadElementDerived for EventTarget { fn is_htmlheadelement(&self) -> bool { match self.type_id { NodeTargetTypeId(ElementNodeTypeId(HTMLHeadElementTypeId)) => true, _ => false } } } impl HTMLHeadElement { pub fn new_inherit...
HTMLHeadElement
identifier_name
const.py
"""Freebox component constants.""" from __future__ import annotations import socket from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import DATA_RATE_KILOBYTES_PER_SECOND, PERCENTAGE, Platform DOMAIN = "freebox" SERVICE_REBOOT = "reboot" APP_DESC = { "app_id": "hass",...
DEFAULT_DEVICE_NAME = "Unknown device" # to store the cookie STORAGE_KEY = DOMAIN STORAGE_VERSION = 1 CONNECTION_SENSORS: tuple[SensorEntityDescription, ...] = ( SensorEntityDescription( key="rate_down", name="Freebox download speed", native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SE...
"device_name": socket.gethostname(), } API_VERSION = "v6" PLATFORMS = [Platform.BUTTON, Platform.DEVICE_TRACKER, Platform.SENSOR, Platform.SWITCH]
random_line_split
sort.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/. */ //! In-place sorting. fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: i...
#[cfg(test)] pub mod test { use std::rand; use std::rand::Rng; use sort; #[test] pub fn random() { let mut rng = rand::task_rng(); for _ in range(0, 50000) { let len: uint = rng.gen(); let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collec...
{ if arr.len() <= 1 { return } let len = arr.len(); quicksort_helper(arr, 0, (len - 1) as int); }
identifier_body
sort.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/. */ //! In-place sorting. fn
<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) { if right <= left { return } let mut i: int = left - 1; let mut j: int = right; let mut p: int = i; let mut q: int = j; unsafe { let v: *mut T = &mut arr[right as uint]; loop { i...
quicksort_helper
identifier_name
sort.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/. */ //! In-place sorting. fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: i...
arr.swap(i as uint, j as uint); if arr[i as uint] == (*v) { p += 1; arr.swap(p as uint, i as uint) } if (*v) == arr[j as uint] { q -= 1; arr.swap(j as uint, q as uint) } } } arr....
{ break }
conditional_block
sort.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/. */
fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) { if right <= left { return } let mut i: int = left - 1; let mut j: int = right; let mut p: int = i; let mut q: int = j; unsafe { let v: *mut T = &mut arr[right as uint]; ...
//! In-place sorting.
random_line_split
projections.py
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
input=[ full_matrix_projection(input=m5), trans_full_matrix_projection(input=m6), full_matrix_projection(input=m7), full_matrix_projection(input=m8) ], size=100, layer_attr=ExtraAttr( drop_rate=0.5, error_clipping_threshold=40)) outputs(end)
trans=True) end = mixed_layer(
random_line_split
membership-add-on.module.ts
import {Server} from "../../../core/server"; import {PassportService} from "../../passport/service/passport.service";
import {MembershipAddOnRepository} from "./repository/membership-add-on.repository"; import {MembershipAddOnSocketComponent} from "./component/membership-add-on-socket.component"; export class MembershipAddOnModule { service: MembershipAddOnService; component: MembershipAddOnComponent; routes: MembershipAd...
import {MembershipAddOnService} from "./service/membership-add-on.service"; import {MembershipAddOnComponent} from "./component/membership-add-on.component"; import {MembershipAddOnSocketRoutes} from "./routes/membership-add-on-socket.routes";
random_line_split
membership-add-on.module.ts
import {Server} from "../../../core/server"; import {PassportService} from "../../passport/service/passport.service"; import {MembershipAddOnService} from "./service/membership-add-on.service"; import {MembershipAddOnComponent} from "./component/membership-add-on.component"; import {MembershipAddOnSocketRoutes} from "....
{ service: MembershipAddOnService; component: MembershipAddOnComponent; routes: MembershipAddOnSocketRoutes; constructor(passportService: PassportService, MembershipAddOnRepository: MembershipAddOnRepository, server: Server) { this.service = new MembershipAddOnS...
MembershipAddOnModule
identifier_name
group.py
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Li...
def remote_join_group(request, message, groupid): group = models.BookiGroup.objects.get(url_name=groupid) group.members.add(request.user) transaction.commit() return {"result": True}
random_line_split
group.py
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Li...
(request, message, groupid): from booki.statusnet.models import searchMessages group = models.BookiGroup.objects.get(url_name=groupid) mess = searchMessages('%%23%s' % group.url_name) # remove this hard code messages = ['<a href="http://status.flossmanuals.net/notice/%s">%s: %s</a>' % (m['id'], m[...
remote_get_status_messages
identifier_name
group.py
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Li...
return {} def remote_leave_group(request, message, groupid): group = models.BookiGroup.objects.get(url_name=groupid) group.members.remove(request.user) transaction.commit() return {"result": True} def remote_join_group(request, message, groupid): group = models.BookiGroup.objects.get(url_na...
try: sputnik.sadd("sputnik:channel:%s:users" % message["channel"], request.user.username) except: pass
conditional_block
group.py
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Li...
group = models.BookiGroup.objects.get(url_name=groupid) group.members.add(request.user) transaction.commit() return {"result": True}
identifier_body
task-killjoin.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 ...
// Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End:
{ task::spawn_unlinked(supervisor) }
identifier_body
task-killjoin.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 ...
// currently not needed because the supervisor runs first, but I can // imagine that changing. task::yield(); fail!(); } fn supervisor() { // Unsupervise this task so the process doesn't return a failure status as // a result of the main task being killed. let f = supervised; task::try(...
fn supervised() { // Yield to make sure the supervisor joins before we fail. This is
random_line_split
task-killjoin.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 ...
() { // Yield to make sure the supervisor joins before we fail. This is // currently not needed because the supervisor runs first, but I can // imagine that changing. task::yield(); fail!(); } fn supervisor() { // Unsupervise this task so the process doesn't return a failure status as // a ...
supervised
identifier_name
interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.js
var interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore = [ [ "getDevices", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a31af140046e965889b1e344e53ab37e1", null ], [ "getMaster", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a2bed6e1e4895ca63cb4e5bd55c15e48f"...
[ "getTermFor", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#af1f35746cf3838fc0b143fb8c8baae5d", null ], [ "relinquishAllRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#ab1d5f9847d612b2884a86ce70f476404", null ], [ "relinquishRole", "interfaceorg_1_1onosprojec...
[ "getNodes", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#afb48638578c77456adf13f1cd46614c7", null ], [ "getRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#ac2d2cf6f0fc0057267ce7b285bdb91e7", null ],
random_line_split
eval_assignment.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn returns_expression() { assert_eval_val( "(define x 0) (set! x (+ x 1))", unspecified(), ); } #[test] fn overwrites_variables() { assert_eval( "(define x 0) (set! x (+ x 1)) ...
() { assert_eval( "(define (gen-counter) (define counter 0) (lambda () (set! counter (+ counter 1)) counter)) (define count (gen-counter)) (count) (count) (count)", "3", ); } #[test] fn malformed_variable_name()...
overwrites_variables_in_captured_scopes
identifier_name
eval_assignment.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn returns_expression() { assert_eval_val( "(define x 0) (set! x (+ x 1))", unspecified(), ); } #[test] fn overwrites_variables() { assert_eval( "(define x 0) (set! x (+ x 1)) ...
"3", ); } #[test] fn malformed_variable_name() { assert_eval_err("(set! 3 3)", MalformedExpression); } #[test] fn unknown_variable() { assert_eval_err("(set! x 3)", UnboundVariable("x".into())); } #[test] fn wrong_arguments_number() { assert_eval_err("(set!)", BadArity(Some("set!".into()))); ...
random_line_split
eval_assignment.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn returns_expression() { assert_eval_val( "(define x 0) (set! x (+ x 1))", unspecified(), ); } #[test] fn overwrites_variables() { assert_eval( "(define x 0) (set! x (+ x 1)) ...
#[test] fn unknown_variable() { assert_eval_err("(set! x 3)", UnboundVariable("x".into())); } #[test] fn wrong_arguments_number() { assert_eval_err("(set!)", BadArity(Some("set!".into()))); assert_eval_err("(set! x)", BadArity(Some("set!".into()))); assert_eval_err("(set! x 2 3)", BadArity(Some("set!...
{ assert_eval_err("(set! 3 3)", MalformedExpression); }
identifier_body
production.py
# In production set the environment variable like this: # DJANGO_SETTINGS_MODULE=my_proj.settings.production from .base import * # NOQA import logging.config # For security and performance reasons, DEBUG is turned off DEBUG = False # Must mention ALLOWED_HOSTS in production! ALLOWED_HOSTS = ['172.16.0....
logging.config.dictConfig(LOGGING)
app_handler = '%s_log_file' % app app_log_filepath = '%s.log' % app LOGGING['loggers'][app] = { 'handlers': [app_handler, 'console', ], 'level': 'DEBUG', } LOGGING['handlers'][app_handler] = { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': join(LOGF...
conditional_block
production.py
# In production set the environment variable like this: # DJANGO_SETTINGS_MODULE=my_proj.settings.production from .base import * # NOQA import logging.config # For security and performance reasons, DEBUG is turned off DEBUG = False # Must mention ALLOWED_HOSTS in production! ALLOWED_HOSTS = ['172.16.0....
# X_FRAME_OPTIONS = 'DENY' # Log everything to the logs directory at the top LOGFILE_ROOT = join(BASE_DIR, 'logs') # Reset logging LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ( '[%(asctime)s]...
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
random_line_split
DaqDevDiscovery01.py
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
def create_widgets(self): '''Create the tkinter UI''' main_frame = tk.Frame(self) main_frame.pack(fill=tk.X, anchor=tk.NW) discover_button = tk.Button(main_frame) discover_button["text"] = "Discover DAQ Devices" discover_button["command"] = self.discover_devices ...
descriptor = self.inventory[selected_index] # Update the device ID label self.device_id_label["text"] = descriptor.unique_id # Create the DAQ device from the descriptor # For performance reasons, it is not recommended to create # and release the device every ...
conditional_block
DaqDevDiscovery01.py
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
if inventory_count > 0 and selected_index < inventory_count: descriptor = self.inventory[selected_index] # Update the device ID label self.device_id_label["text"] = descriptor.unique_id # Create the DAQ device from the descriptor # For performance re...
ul.release_daq_device(self.board_num) self.device_created = False
random_line_split
DaqDevDiscovery01.py
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
(self): try: # Flash the device LED ul.flash_led(self.board_num) except ULError as e: show_ul_error(e) def selected_device_changed(self, *args): # @UnusedVariable selected_index = self.devices_combobox.current() inventory_count = len(self.invento...
flash_led
identifier_name
DaqDevDiscovery01.py
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
# Start the example if this module is being run if __name__ == "__main__": # Start the example DaqDevDiscovery01(master=tk.Tk()).mainloop()
def __init__(self, master): super(DaqDevDiscovery01, self).__init__(master) self.board_num = 0 self.device_created = False # Tell the UL to ignore any boards configured in InstaCal ul.ignore_instacal() self.create_widgets() def discover_devices(self): sel...
identifier_body
urlmap.py
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
(self, app, app_url): def wrap(environ, start_response): environ['SCRIPT_NAME'] += app_url return app(environ, start_response) return wrap def _munge_path(self, app, path_info, app_url): def wrap(environ, start_response): environ['SCRIPT_NAME'] += app_ur...
_set_script_name
identifier_name
urlmap.py
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
"""Parse header into content type and options. Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('Content-Type: text/html; mimetype=text/html') ('Content-Type:', {'mimetype': 'text/html'}) :param value: the header to parse. :...
def parse_options_header(value):
random_line_split
urlmap.py
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
parts = _tokenize(';' + value) name = next(parts)[0] extra = dict(parts) return name, extra class Accept(object): def __init__(self, value): self._content_types = [parse_options_header(v) for v in parse_list_header(value)] def best_match(self, supporte...
return '', {}
conditional_block
urlmap.py
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
def _content_type_strategy(self, host, port, environ): """Check Content-Type header for API version.""" app = None params = parse_options_header(environ.get('CONTENT_TYPE', ''))[1] if 'version' in params: app, app_url = self._match(host, port, '/v' + params['version']) ...
"""Check path suffix for MIME type and path prefix for API version.""" mime_type = app = app_url = None parts = path_info.rsplit('.', 1) if len(parts) > 1: possible_type = 'application/' + parts[1] if possible_type in wsgi.SUPPORTED_CONTENT_TYPES: mime_ty...
identifier_body
run-ci-e2e-tests.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /** * This script tests that React Native end to end installation/bootstrap works for different platforms * Available a...
cp(`${SCRIPTS}/android-e2e-test.js`, 'android-e2e-test.js'); cd('android'); echo('Downloading Maven deps'); exec('./gradlew :app:copyDownloadableDepsToLibs'); // Make sure we installed local version of react-native if (!test('-e', path.basename(MARKER_ANDROID))) { echo('Android marker was...
{ echo('Failed to install appium'); echo('Most common reason is npm registry connectivity, try again'); exitCode = 1; throw Error(exitCode); }
conditional_block
run-ci-e2e-tests.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /** * This script tests that React Native end to end installation/bootstrap works for different platforms * Available a...
if (tryExecNTimes( () => { exec('sleep 10s'); if (argv.tvos) { return exec('xcodebuild -destination "platform=tvOS Simulator,name=Apple TV 1080p,OS=10.0" -scheme EndToEndTest-tvOS -sdk appletvsimulator test | xcpretty && exit ${PIPESTATUS[0]}').code; } else { return...
echo('Executing ' + iosTestType + ' e2e test');
random_line_split
author.py
from whiffle import wikidotapi from util import hook @hook.command def
(inp): ".author <Author Name> -- Will return details regarding the author" if firstrefresh == 0:#make sure the cache actually exists return "Cache has not yet updated, please wait a minute and search again." api = wikidotapi.connection() api.Site = "wanderers-library" pages = api.refresh_pages() authpages = [] ...
author
identifier_name
author.py
from whiffle import wikidotapi from util import hook @hook.command def author(inp): ".author <Author Name> -- Will return details regarding the author" if firstrefresh == 0:#make sure the cache actually exists return "Cache has not yet updated, please wait a minute and search again." api = wikidotapi.connection()...
return "nonick::"+ authorpage+""+author +" has written " + str(pagetotal) + " pages. They have " + str(totalrating)+ " net upvotes with an average rating of " + str(avgrating) + ". Their most recent article is " + pagetitle + "(Rating:" + str(pagerating) + ")"#+"- http://wanderers-library.wikidot.com/" + au...
return "Author not found."
conditional_block
author.py
from whiffle import wikidotapi from util import hook @hook.command def author(inp):
".author <Author Name> -- Will return details regarding the author" if firstrefresh == 0:#make sure the cache actually exists return "Cache has not yet updated, please wait a minute and search again." api = wikidotapi.connection() api.Site = "wanderers-library" pages = api.refresh_pages() authpages = [] totalra...
identifier_body
author.py
from whiffle import wikidotapi from util import hook @hook.command def author(inp): ".author <Author Name> -- Will return details regarding the author" if firstrefresh == 0:#make sure the cache actually exists return "Cache has not yet updated, please wait a minute and search again." api = wikidotapi.connection()...
avgrating = totalrating/pagetotal if not authpages: #if no author pages are added return "Author not found." return "nonick::"+ authorpage+""+author +" has written " + str(pagetotal) + " pages. They have " + str(totalrating)+ " net upvotes with an average rating of " + str(avgrating) + ". Their most rece...
random_line_split
dom.ts
import {isBoolean, isString, isArray, isPlainObject} from "./util/types" export type HTMLAttrs = {[name: string]: any} export type HTMLChild = string | HTMLElement | (string | HTMLElement)[] const _createElement = <T extends keyof HTMLElementTagNameMap>(tag: T) => (attrs: HTMLAttrs = {}, ...children: HTMLChild[])...
for (const child of children) { if (isArray(child)) { for (const _child of child) append(_child) } else append(child) } return element } export function createElement<T extends keyof HTMLElementTagNameMap>(tag: T, attrs: HTMLAttrs, ...children: HTMLChild[]): HTMLElementTagName...
{ if (child instanceof HTMLElement) element.appendChild(child) else if (isString(child)) element.appendChild(document.createTextNode(child)) else if (child != null && child !== false) throw new Error(`expected an HTMLElement, string, false or null, got ${JSON.stringify(child)}`) }
identifier_body
dom.ts
import {isBoolean, isString, isArray, isPlainObject} from "./util/types" export type HTMLAttrs = {[name: string]: any} export type HTMLChild = string | HTMLElement | (string | HTMLElement)[] const _createElement = <T extends keyof HTMLElementTagNameMap>(tag: T) => (attrs: HTMLAttrs = {}, ...children: HTMLChild[])...
(el: HTMLElement): Sizing { const style = getComputedStyle(el) return { top: parseFloat(style.paddingTop!) || 0, bottom: parseFloat(style.paddingBottom!) || 0, left: parseFloat(style.paddingLeft!) || 0, right: parseFloat(style.paddingRight!) || 0, } } export enum Keys { Backspace = ...
padding
identifier_name
dom.ts
import {isBoolean, isString, isArray, isPlainObject} from "./util/types" export type HTMLAttrs = {[name: string]: any} export type HTMLChild = string | HTMLElement | (string | HTMLElement)[] const _createElement = <T extends keyof HTMLElementTagNameMap>(tag: T) => (attrs: HTMLAttrs = {}, ...children: HTMLChild[])...
export function padding(el: HTMLElement): Sizing { const style = getComputedStyle(el) return { top: parseFloat(style.paddingTop!) || 0, bottom: parseFloat(style.paddingBottom!) || 0, left: parseFloat(style.paddingLeft!) || 0, right: parseFloat(style.paddingRight!) || 0, } } export en...
right: parseFloat(style.marginRight!) || 0, } }
random_line_split
models.py
""" Models used by the block structure framework. """ from __future__ import absolute_import import errno from contextlib import contextmanager from datetime import datetime from logging import getLogger import six from six.moves import map from django.conf import settings from django.core.exceptions import Suspicio...
(cls, files): """ Deletes the given files from storage. """ storage = _bs_model_storage() list(map(storage.delete, files)) @classmethod def _get_all_files(cls, data_usage_key): """ Returns all filenames that exist for the given key. """ di...
_delete_files
identifier_name
models.py
""" Models used by the block structure framework. """ from __future__ import absolute_import import errno from contextlib import contextmanager from datetime import datetime from logging import getLogger import six from six.moves import map from django.conf import settings from django.core.exceptions import Suspicio...
filename, ) def _bs_model_storage(): """ Get django Storage object for BlockStructureModel. """ return get_storage( settings.BLOCK_STRUCTURES_SETTINGS.get('STORAGE_CLASS'), **settings.BLOCK_STRUCTURES_SETTINGS.get('STORAGE_KWARGS', {}) ) class CustomizableFileField(mo...
random_line_split
models.py
""" Models used by the block structure framework. """ from __future__ import absolute_import import errno from contextlib import contextmanager from datetime import datetime from logging import getLogger import six from six.moves import map from django.conf import settings from django.core.exceptions import Suspicio...
@python_2_unicode_compatible class BlockStructureModel(TimeStampedModel): """ Model for storing Block Structure information. .. no_pii: """ VERSION_FIELDS = [ u'data_version', u'data_edit_timestamp', u'transformers_schema_version', u'block_structure_schema_version...
raise
conditional_block
models.py
""" Models used by the block structure framework. """ from __future__ import absolute_import import errno from contextlib import contextmanager from datetime import datetime from logging import getLogger import six from six.moves import map from django.conf import settings from django.core.exceptions import Suspicio...
@classmethod def update_or_create(cls, serialized_data, data_usage_key, **kwargs): """ Updates or creates the BlockStructureModel entry for the given data_usage_key in the kwargs, uploading serialized_data as the content data. """ # Use an atomic transaction so ...
""" Returns the entry associated with the given data_usage_key. Raises: BlockStructureNotFound if an entry for data_usage_key is not found. """ try: return cls.objects.get(data_usage_key=data_usage_key) except cls.DoesNotExist: log.info(u'Bloc...
identifier_body
mcts.rs
use crate::actions::Action; use crate::Role; use mcts::{statistics, SearchSettings}; use rand::Rng; use search_graph; use std::{cmp, mem}; #[derive(Clone, Debug)] pub struct Game {} impl statistics::two_player::PlayerMapping for Role { fn player_one() -> Self { Role::Dwarf } fn player_two() -> Self { Ro...
crate::state::State, mcts::graph::VertexData, mcts::graph::EdgeData<Game>, >, root: search_graph::view::NodeRef<'id>, mut rng: R, ) -> search_graph::view::EdgeRef<'id> { let mut children = view.children(root); let mut best_child = children.next().unwrap(); let mut best_child_visits = view[best_c...
'id,
random_line_split
mcts.rs
use crate::actions::Action; use crate::Role; use mcts::{statistics, SearchSettings}; use rand::Rng; use search_graph; use std::{cmp, mem}; #[derive(Clone, Debug)] pub struct Game {} impl statistics::two_player::PlayerMapping for Role { fn player_one() -> Self { Role::Dwarf } fn player_two() -> Self { Ro...
}
{ match self.graph_compact { GraphCompact::Prune => { if let Some(node) = self.graph.find_node_mut(state) { search_graph::view::of_node(node, |view, node| { view.retain_reachable_from(Some(node).into_iter()); }); } else { mem::swap(&mut self.graph, &mu...
identifier_body
mcts.rs
use crate::actions::Action; use crate::Role; use mcts::{statistics, SearchSettings}; use rand::Rng; use search_graph; use std::{cmp, mem}; #[derive(Clone, Debug)] pub struct Game {} impl statistics::two_player::PlayerMapping for Role { fn
() -> Self { Role::Dwarf } fn player_two() -> Self { Role::Troll } fn resolve_player(&self) -> statistics::two_player::Player { match *self { Role::Dwarf => statistics::two_player::Player::One, Role::Troll => statistics::two_player::Player::Two, } } } impl mcts::game::State for cr...
player_one
identifier_name
setup.py
from setuptools import setup, find_packages from os.path import join, dirname setup( name="fant_sizer", version="0.7", author="Rypiuk Oleksandr", author_email="ripiuk96@gmail.com", description="fant_sizer command-line file-information", url="https://github.com/ripiuk/fan...
'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 3.6' ...
'Environment :: Console',
random_line_split
jvector.js
/** * JVectormap demo page */ (function ($) { 'use strict'; $('.world-map').vectorMap({ map: 'world_mill_en', backgroundColor: 'transparent', zoomOnScroll: false, strokeWidth: 1, regionStyle: { initial: { fill: $.staticApp.dark, 'fill-opacity': 0.2 }, hover: ...
}, markers: [{ latLng: [41.90, 12.45], name: 'Vatican City' }, { latLng: [43.73, 7.41], name: 'Monaco' }, { latLng: [-0.52, 166.93], name: 'Nauru' }, { latLng: [-8.51, 179.21], name: 'Tuvalu' }, { latLng: [43.93, 12.46], name: 'San Mari...
'stroke-width': 10 }
random_line_split
klopfer.py
import directory import scanner import mapper import board import os class Klopfer(object):
def __init__(self, import_dir, export_dir): self.import_dir = import_dir self.export_dir = export_dir print "Klopfer class" def run(self): # open dir and get oldest file with the given extension dir = directory.Directory(os, self.import_dir, ['jpg', 'jpeg']) self.ima...
identifier_body
klopfer.py
import directory import scanner import mapper import board import os class Klopfer(object): def __init__(self, import_dir, export_dir): self.import_dir = import_dir self.export_dir = export_dir print "Klopfer class" def
(self): # open dir and get oldest file with the given extension dir = directory.Directory(os, self.import_dir, ['jpg', 'jpeg']) self.imagefile = dir.get_oldest_file() # open image scan = scanner.Scanner(self.imagefile.name) self.remove_image() informations = scan...
run
identifier_name
klopfer.py
import directory import scanner import mapper import board import os class Klopfer(object): def __init__(self, import_dir, export_dir): self.import_dir = import_dir self.export_dir = export_dir print "Klopfer class" def run(self): # open dir and get oldest file with the given...
# load board_id and cards mapping = mapper.Mapper(informations) board_id = mapping.board_id cards = mapping.get_cards() # create board current_board = board.Board(board_id, cards) # write board to json current_board.export_json(self.export_dir) # rem...
scan = scanner.Scanner(self.imagefile.name) self.remove_image() informations = scan.scan()
random_line_split