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
type-infer-generalize-ty-var.rs
// Copyright 2016 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 ...
static x: usize = 42; &x } } impl Get<usize> for Wrap<U> { fn get(&self) -> &usize { static x: usize = 55; &x } } trait MyShow { fn dummy(&self) { } } impl<'a> MyShow for &'a (MyShow + 'a) { } impl MyShow for usize { } fn constrain<'a>(rc: RefCell<&'a (MyShow + 'a)>) { } f...
fn get(&self) -> &(MyShow + 'static) {
random_line_split
convert_to_constraints.js
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var Lib = require('../../lib'); // The contour extraction is great, except it totally fails for constraints bec...
pathinfo.pop(); break; case '>=': case '>': if(pathinfo.length !== 1) { Lib.warn('Contour data invalid for the specified inequality operation.'); return; } // In this case there should be exactly two contour l...
{ pi0.paths.push(op1(pi1.paths.shift())); }
conditional_block
convert_to_constraints.js
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var Lib = require('../../lib'); // The contour extraction is great, except it totally fails for constraints bec...
// simply concatenate the info into one pathinfo and flip all of the data // in one. This will draw the contour as closed. pi0 = pathinfo[0]; for(i = 0; i < pi0.edgepaths.length; i++) { pi0.edgepaths[i] = op0(pi0.edgepaths[i]); } ...
Lib.warn('Contour data invalid for the specified inequality operation.'); return; } // In this case there should be exactly two contour levels in pathinfo. We
random_line_split
primitives_scale.rs
extern crate rand; extern crate kiss3d; extern crate nalgebra as na; use rand::random; use na::{Vec3, Translation, RotationWithTranslation}; use kiss3d::window::Window; use kiss3d::light::Light; fn main() { let mut window = Window::new("Kiss3d: primitives_scale"); // NOTE: scaling is not possible. for i ...
sp.set_color(random(), random(), random()); co.set_color(random(), random(), random()); cy.set_color(random(), random(), random()); ca.set_color(random(), random(), random()); } window.set_light(Light::StickToCamera); while window.render() { // XXX: applying this to...
ca.append_translation(&Vec3::new(offset, 0.0, 0.0)); cu.set_color(random(), random(), random());
random_line_split
primitives_scale.rs
extern crate rand; extern crate kiss3d; extern crate nalgebra as na; use rand::random; use na::{Vec3, Translation, RotationWithTranslation}; use kiss3d::window::Window; use kiss3d::light::Light; fn main()
{ let mut window = Window::new("Kiss3d: primitives_scale"); // NOTE: scaling is not possible. for i in 0usize .. 11 { let dim: f32 = random::<f32>() / 2.0; let dim2 = dim / 2.0; let offset = i as f32 * 1.0 - 5.0; let mut cu = window.add_cube(dim2, dim2, dim2); let ...
identifier_body
primitives_scale.rs
extern crate rand; extern crate kiss3d; extern crate nalgebra as na; use rand::random; use na::{Vec3, Translation, RotationWithTranslation}; use kiss3d::window::Window; use kiss3d::light::Light; fn
() { let mut window = Window::new("Kiss3d: primitives_scale"); // NOTE: scaling is not possible. for i in 0usize .. 11 { let dim: f32 = random::<f32>() / 2.0; let dim2 = dim / 2.0; let offset = i as f32 * 1.0 - 5.0; let mut cu = window.add_cube(dim2, dim2, dim2); l...
main
identifier_name
context.rs
//! Manage OpenGL context and window. use std::string::ToString; use std::rc::Rc; use std::ops::Deref; use std::cell::{UnsafeCell, RefCell, RefMut, Ref}; use glium::{Display, DisplayBuild}; use glium::glutin::WindowBuilder; pub use glium::{Frame, Surface, SwapBuffersError, DrawError}; /// Just a reference of `Contex...
} }
random_line_split
context.rs
//! Manage OpenGL context and window. use std::string::ToString; use std::rc::Rc; use std::ops::Deref; use std::cell::{UnsafeCell, RefCell, RefMut, Ref}; use glium::{Display, DisplayBuild}; use glium::glutin::WindowBuilder; pub use glium::{Frame, Surface, SwapBuffersError, DrawError}; /// Just a reference of `Contex...
(&self) -> Ref<Frame> { unsafe { let cell = self.get_cell(); if cell.is_none() { panic!("Frame not exist.") } cell.as_ref().unwrap().borrow() } } /// Get frame mutable reference. /// # Panics /// Panic if something is borro...
get_frame
identifier_name
context.rs
//! Manage OpenGL context and window. use std::string::ToString; use std::rc::Rc; use std::ops::Deref; use std::cell::{UnsafeCell, RefCell, RefMut, Ref}; use glium::{Display, DisplayBuild}; use glium::glutin::WindowBuilder; pub use glium::{Frame, Surface, SwapBuffersError, DrawError}; /// Just a reference of `Contex...
} } /// Get frame immutable reference. /// # Panics /// Panic if frame not created or something is mutable borrowing the frame. pub fn get_frame(&self) -> Ref<Frame> { unsafe { let cell = self.get_cell(); if cell.is_none() { panic!("Frame no...
{ let mut frame = self.display.draw(); frame.clear_color_and_depth(self.clear_color, 1.0); *cell = Some(RefCell::new(frame)); }
conditional_block
context.rs
//! Manage OpenGL context and window. use std::string::ToString; use std::rc::Rc; use std::ops::Deref; use std::cell::{UnsafeCell, RefCell, RefMut, Ref}; use glium::{Display, DisplayBuild}; use glium::glutin::WindowBuilder; pub use glium::{Frame, Surface, SwapBuffersError, DrawError}; /// Just a reference of `Contex...
} impl Deref for Gfx { type Target = Context; fn deref(&self) -> &Context { &*self.0 } } /// Context handle object. /// /// Manage `glium::Display` context and current frame. pub struct Context { pub display: Display, frame: UnsafeCell<Option<RefCell<Frame>>>, clear_color: (f32, f3...
{ Gfx(Rc::new(ctx)) }
identifier_body
GenericRequestMapper.spec.ts
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "...
import { GenericRequestMapper } from '../../../../lib/dispatcher/request/mapper/GenericRequestMapper'; import { MockAlwaysFalseRequestHandler } from '../../../mocks/request/MockAlwaysFalseRequestHandler'; import { MockAlwaysTrueRequestHandler } from '../../../mocks/request/MockAlwaysTrueRequestHandler'; describe('Gene...
import { GenericRequestHandlerChain } from '../../../../lib/dispatcher/request/handler/GenericRequestHandlerChain';
random_line_split
0028_dancepieces_to_works.py
# Generated by Django 2.0 on 2018-02-08 11:45 from django.db import migrations def forwards(apps, schema_editor):
class Migration(migrations.Migration): dependencies = [ ("spectator_events", "0027_classicalworks_to_works"), ] operations = [ migrations.RunPython(forwards), ]
""" Change all DancePiece objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the DancePiece. """ DancePiece = apps.get_model("spectator_events", "DancePiece") Work = apps.get_model("spectator_events", "Work") WorkRole = apps.get_model("specta...
identifier_body
0028_dancepieces_to_works.py
# Generated by Django 2.0 on 2018-02-08 11:45 from django.db import migrations def forwards(apps, schema_editor): """ Change all DancePiece objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the DancePiece. """ DancePiece = apps.get_model("spe...
(migrations.Migration): dependencies = [ ("spectator_events", "0027_classicalworks_to_works"), ] operations = [ migrations.RunPython(forwards), ]
Migration
identifier_name
0028_dancepieces_to_works.py
# Generated by Django 2.0 on 2018-02-08 11:45 from django.db import migrations def forwards(apps, schema_editor): """ Change all DancePiece objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the DancePiece. """ DancePiece = apps.get_model("spe...
dp.delete() class Migration(migrations.Migration): dependencies = [ ("spectator_events", "0027_classicalworks_to_works"), ] operations = [ migrations.RunPython(forwards), ]
WorkSelection.objects.create( event=selection.event, work=work, order=selection.order )
conditional_block
0028_dancepieces_to_works.py
# Generated by Django 2.0 on 2018-02-08 11:45 from django.db import migrations def forwards(apps, schema_editor): """ Change all DancePiece objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the DancePiece. """ DancePiece = apps.get_model("spe...
work = Work.objects.create( kind="dancepiece", title=dp.title, title_sort=dp.title_sort ) for role in dp.roles.all(): WorkRole.objects.create( creator=role.creator, work=work, role_name=role.role_name, role_...
WorkRole = apps.get_model("spectator_events", "WorkRole") WorkSelection = apps.get_model("spectator_events", "WorkSelection") for dp in DancePiece.objects.all():
random_line_split
calib.py
# # My first attempt at python # calibrate accelerometer # import re import scipy from scipy import optimize from scipy import linalg from pylab import * # # parse the log # def read_log(ac_id, filename, sensor): f = open(filename, 'r') pattern = re.compile("(\S+) "+ac_id+" IMU_"+sensor+"_RAW (\S+) (\S+) (\S+...
m=re.match(pattern, line) if m: list_meas.append([float(m.group(2)), float(m.group(3)), float(m.group(4))]) return scipy.array(list_meas) # # select only non-noisy data # def filter_meas(meas, window_size, noise_threshold): filtered_meas = [] filtered_idx = [] for i in rang...
break
conditional_block
calib.py
# # My first attempt at python # calibrate accelerometer # import re import scipy from scipy import optimize from scipy import linalg from pylab import * # # parse the log # def read_log(ac_id, filename, sensor): f = open(filename, 'r') pattern = re.compile("(\S+) "+ac_id+" IMU_"+sensor+"_RAW (\S+) (\S+) (\S+...
subplot(3,2,5) plot(cp1[:,0]); plot(cp1[:,1]); plot(cp1[:,2]); plot(-sensor_ref*scipy.ones(len(flt_meas))); plot(sensor_ref*scipy.ones(len(flt_meas))); subplot(3,2,6) plot(np1); plot(sensor_ref*scipy.ones(len(flt_meas))); show();
subplot(3,2,4) plot(np0); plot(sensor_ref*scipy.ones(len(flt_meas)));
random_line_split
calib.py
# # My first attempt at python # calibrate accelerometer # import re import scipy from scipy import optimize from scipy import linalg from pylab import * # # parse the log # def read_log(ac_id, filename, sensor): f = open(filename, 'r') pattern = re.compile("(\S+) "+ac_id+" IMU_"+sensor+"_RAW (\S+) (\S+) (\S+...
(meas, scale): max_meas = meas[:,:].max(axis=0) min_meas = meas[:,:].min(axis=0) n = (max_meas + min_meas) / 2 sf = 2*scale/(max_meas - min_meas) return scipy.array([n[0], n[1], n[2], sf[0], sf[1], sf[2]]) # # scale the set of measurements # def scale_measurements(meas, p): l_comp = []; l_n...
get_min_max_guess
identifier_name
calib.py
# # My first attempt at python # calibrate accelerometer # import re import scipy from scipy import optimize from scipy import linalg from pylab import * # # parse the log # def read_log(ac_id, filename, sensor): f = open(filename, 'r') pattern = re.compile("(\S+) "+ac_id+" IMU_"+sensor+"_RAW (\S+) (\S+) (\S+...
# # scale the set of measurements # def scale_measurements(meas, p): l_comp = []; l_norm = []; for m in meas[:,]: sm = (m - p[0:3])*p[3:6] l_comp.append(sm) l_norm.append(linalg.norm(sm)) return scipy.array(l_comp), scipy.array(l_norm) # # print xml for airframe file # def pri...
max_meas = meas[:,:].max(axis=0) min_meas = meas[:,:].min(axis=0) n = (max_meas + min_meas) / 2 sf = 2*scale/(max_meas - min_meas) return scipy.array([n[0], n[1], n[2], sf[0], sf[1], sf[2]])
identifier_body
error.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Utilities to throw exceptions from Rust bindings. #[cfg(feature = "js_backtrace")] use crate::dom::bindings:...
LAST_EXCEPTION_BACKTRACE.with(|backtrace| { if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() { if let Some(stack) = js_backtrace { eprintln!("JS backtrace:\n{}", stack); } eprintln!("Rust backtrace:\n{}", ...
); #[cfg(feature = "js_backtrace")] {
random_line_split
error.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Utilities to throw exceptions from Rust bindings. #[cfg(feature = "js_backtrace")] use crate::dom::bindings:...
{ /// The error message. pub message: String, /// The file name. pub filename: String, /// The line number. pub lineno: c_uint, /// The column number. pub column: c_uint, } impl ErrorInfo { unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {...
ErrorInfo
identifier_name
error.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Utilities to throw exceptions from Rust bindings. #[cfg(feature = "js_backtrace")] use crate::dom::bindings:...
JS_ClearPendingException(cx); let error_info = if value.is_object() { rooted!(in(cx) let object = value.to_object()); ErrorInfo::from_native_error(cx, object.handle()) .or_else(|| ErrorInfo::from_dom_exception(object.handle())) .unwrap_or_else(|| ErrorInfo { ...
{ JS_ClearPendingException(cx); error!("Uncaught exception: JS_GetPendingException failed"); return; }
conditional_block
error.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Utilities to throw exceptions from Rust bindings. #[cfg(feature = "js_backtrace")] use crate::dom::bindings:...
impl Error { /// Convert this error value to a JS value, consuming it in the process. pub unsafe fn to_jsval( self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue, ) { assert!(!JS_IsExceptionPending(cx)); throw_dom_exception(cx, global, s...
{ debug_assert!(!JS_IsExceptionPending(cx)); let error = format!( "\"this\" object does not implement interface {}.", proto_id_to_name(proto_id) ); throw_type_error(cx, &error); }
identifier_body
phone-detail.component.ts
// #docplaster // #docregion declare var angular: angular.IAngularStatic; import { downgradeComponent } from '@angular/upgrade/static'; // #docregion initialclass
import { Component } from '@angular/core'; import { Phone, PhoneData } from '../core/phone/phone.service'; // #enddocregion initialclass import { RouteParams } from '../ajs-upgraded-providers'; // #docregion initialclass @Component({ selector: 'phone-detail', templateUrl: './phone-detail.template.html', // #end...
random_line_split
phone-detail.component.ts
// #docplaster // #docregion declare var angular: angular.IAngularStatic; import { downgradeComponent } from '@angular/upgrade/static'; // #docregion initialclass import { Component } from '@angular/core'; import { Phone, PhoneData } from '../core/phone/phone.service'; // #enddocregion initialclass import { RoutePara...
(routeParams: RouteParams, phone: Phone) { phone.get(routeParams['phoneId']).subscribe(phone => { this.phone = phone; this.setImage(phone.images[0]); }); } setImage(imageUrl: string) { this.mainImageUrl = imageUrl; } } // #enddocregion initialclass angular.module('phoneDetail') .direct...
constructor
identifier_name
en-MH.js
Bridge.merge(new System.Globalization.CultureInfo("en-MH", true), { englishName: "English (Marshall Islands)",
nativeName: "English (Marshall Islands)", numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), { nanSymbol: "NaN", negativeSign: "-", positiveSign: "+", negativeInfinitySymbol: "-∞", positiveInfinitySymbol: "∞", percentSymbol: "%", perc...
random_line_split
cache.py
import time import os import sys import hashlib import gc import shutil import platform import errno import logging try: import cPickle as pickle except: import pickle from parso._compatibility import FileNotFoundError LOG = logging.getLogger(__name__) _PICKLE_VERSION = 30 """ Version number (integer) for ...
(hashed_grammar, path, p_time, cache_path=None): cache_path = _get_hashed_path(hashed_grammar, path, cache_path=cache_path) try: try: if p_time > os.path.getmtime(cache_path): # Cache is outdated return None except OSError as e: if e.errno ...
_load_from_file_system
identifier_name
cache.py
import time import os import sys import hashlib import gc import shutil import platform import errno import logging try: import cPickle as pickle except: import pickle from parso._compatibility import FileNotFoundError LOG = logging.getLogger(__name__) _PICKLE_VERSION = 30 """ Version number (integer) for ...
module_cache_item = parser_cache[hashed_grammar][path] if p_time <= module_cache_item.change_time: return module_cache_item.node except KeyError: return _load_from_file_system(hashed_grammar, path, p_time, cache_path=cache_path) def _load_from_file_system(hashed_grammar, path, ...
return None try:
random_line_split
cache.py
import time import os import sys import hashlib import gc import shutil import platform import errno import logging try: import cPickle as pickle except: import pickle from parso._compatibility import FileNotFoundError LOG = logging.getLogger(__name__) _PICKLE_VERSION = 30 """ Version number (integer) for ...
_default_cache_path = _get_default_cache_path() """ The path where the cache is stored. On Linux, this defaults to ``~/.cache/parso/``, on OS X to ``~/Library/Caches/Parso/`` and on Windows to ``%LOCALAPPDATA%\\Parso\\Parso\\``. On Linux, if environment variable ``$XDG_CACHE_HOME`` is set, ``$XDG_CACHE_HOME/parso`` ...
if platform.system().lower() == 'windows': dir_ = os.path.join(os.getenv('LOCALAPPDATA') or '~', 'Parso', 'Parso') elif platform.system().lower() == 'darwin': dir_ = os.path.join('~', 'Library', 'Caches', 'Parso') else: dir_ = os.path.join(os.getenv('XDG_CACHE_HOME') or '~/.cache', 'pars...
identifier_body
cache.py
import time import os import sys import hashlib import gc import shutil import platform import errno import logging try: import cPickle as pickle except: import pickle from parso._compatibility import FileNotFoundError LOG = logging.getLogger(__name__) _PICKLE_VERSION = 30 """ Version number (integer) for ...
with open(cache_path, 'rb') as f: gc.disable() try: module_cache_item = pickle.load(f) finally: gc.enable() except FileNotFoundError: return None else: parser_cache.setdefault(hashed_grammar, {})[path] = module_cache_i...
raise
conditional_block
setup.py
from setuptools import setup setup( name='bdranalytics',
author='bigdatarepublic', author_email='info@bigdatarepublic.nl', url='http://www.bigdatarepublic.nl', long_description="README.md", packages=['bdranalytics', 'bdranalytics.images', 'bdranalytics.keras', 'bdranalytics.pdlearn', 'bdranalytics.pl...
version='0.3', license='Apache License 2.0',
random_line_split
controller.rs
pub struct Controller<T: PartialEq> { pub dpad: DPad<T>, } impl<T: PartialEq> Controller<T> { pub fn new(up: T, left: T, down: T, right: T) -> Controller<T> { Controller { dpad: DPad::new(up, left, down, right), } } pub fn down(&mut self, key: &T) { self.dpad.down(key); } pub fn up(&mut...
else { (x.powi(2) + y.powi(2)).sqrt() }; [x / z, y / z] } }
{ 1.0 }
conditional_block
controller.rs
pub struct Controller<T: PartialEq> { pub dpad: DPad<T>, } impl<T: PartialEq> Controller<T> { pub fn new(up: T, left: T, down: T, right: T) -> Controller<T> { Controller { dpad: DPad::new(up, left, down, right), } } pub fn down(&mut self, key: &T) { self.dpad.down(key); } pub fn up(&mut...
pub fn down(&mut self, key: &T) { for (idx, bind) in self.bindings.iter().enumerate() { if key == bind { self.state[idx] = true; } } } pub fn up(&mut self, key: &T) { for (idx, bind) in self.bindings.iter().enumerate() { if key == bind { self.state[idx] = false; ...
state: [false; 4], } }
random_line_split
controller.rs
pub struct Controller<T: PartialEq> { pub dpad: DPad<T>, } impl<T: PartialEq> Controller<T> { pub fn
(up: T, left: T, down: T, right: T) -> Controller<T> { Controller { dpad: DPad::new(up, left, down, right), } } pub fn down(&mut self, key: &T) { self.dpad.down(key); } pub fn up(&mut self, key: &T) { self.dpad.up(key); } } pub struct DPad<T: PartialEq> { bindings: [T; 4], state: ...
new
identifier_name
test_tracepoint.py
#!/usr/bin/env python # Copyright (c) Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") import bcc import unittest from time import sleep import distutils.version import os import subprocess def kernel_version_ge(major, minor): # True if running kernel is >= X.Y version = distu...
return True @unittest.skipUnless(kernel_version_ge(4,7), "requires kernel >= 4.7") class TestTracepoint(unittest.TestCase): def test_tracepoint(self): text = """ BPF_HASH(switches, u32, u64); TRACEPOINT_PROBE(sched, sched_switch) { u64 val = 0; u32 pid = args->n...
return False
conditional_block
test_tracepoint.py
#!/usr/bin/env python # Copyright (c) Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") import bcc import unittest from time import sleep import distutils.version import os import subprocess def kernel_version_ge(major, minor): # True if running kernel is >= X.Y version = distu...
(self): text = """ BPF_HASH(switches, u32, u64); TRACEPOINT_PROBE(sched, sched_switch) { u64 val = 0; u32 pid = args->next_pid; u64 *existing = switches.lookup_or_init(&pid, &val); (*existing)++; return 0; } """ ...
test_tracepoint
identifier_name
test_tracepoint.py
#!/usr/bin/env python # Copyright (c) Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") import bcc import unittest from time import sleep import distutils.version import os import subprocess def kernel_version_ge(major, minor): # True if running kernel is >= X.Y version = distu...
@unittest.skipUnless(kernel_version_ge(4,7), "requires kernel >= 4.7") class TestTracepointDataLoc(unittest.TestCase): def test_tracepoint_data_loc(self): text = """ struct value_t { char filename[64]; }; BPF_HASH(execs, u32, struct value_t); TRACEPOINT_PROBE(sche...
total_switches = 0 for k, v in b["switches"].items(): total_switches += v.value self.assertNotEqual(0, total_switches)
random_line_split
test_tracepoint.py
#!/usr/bin/env python # Copyright (c) Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") import bcc import unittest from time import sleep import distutils.version import os import subprocess def kernel_version_ge(major, minor): # True if running kernel is >= X.Y version = distu...
if __name__ == "__main__": unittest.main()
text = """ struct value_t { char filename[64]; }; BPF_HASH(execs, u32, struct value_t); TRACEPOINT_PROBE(sched, sched_process_exec) { struct value_t val = {0}; char fn[64]; u32 pid = args->pid; struct value_t *existing = execs.l...
identifier_body
elmap.js
var assert = require('chai').assert; var ElMap = require('../uglymol').ElMap; var util = require('../perf/util'); /* Note: axis order in ccp4 maps is tricky. It was tested by re-sectioning, * i.e. changing axis order, of a map with CCP4 mapmask: mapmask mapin 1mru_2mFo-DFc.ccp4 mapout 1mru_yzx.ccp4 << eof AXIS ...
}); });
{ assert.closeTo(dmap.unit_cell.parameters[i], cmap.unit_cell.parameters[i], 0.02); }
conditional_block
elmap.js
var assert = require('chai').assert; var ElMap = require('../uglymol').ElMap; var util = require('../perf/util'); /* Note: axis order in ccp4 maps is tricky. It was tested by re-sectioning,
* i.e. changing axis order, of a map with CCP4 mapmask: mapmask mapin 1mru_2mFo-DFc.ccp4 mapout 1mru_yzx.ccp4 << eof AXIS Y Z X MODE mapin eof */ describe('ElMap', function () { 'use strict'; var dmap_buf = util.open_as_array_buffer('1mru.omap'); var cmap_buf = util.open_as_array_buffer('1mru.map'); v...
random_line_split
example.rs
use std::cmp::Ordering::Equal; use std::collections::HashMap; enum GameResult { Win, Draw, Loss } struct TeamResult { wins: u32, draws: u32, losses: u32, } impl TeamResult { fn new() -> TeamResult { TeamResult { wins: 0, draws: 0, losses: 0 } } fn add_game_result(&mut self...
(input: &str) -> String { let mut results: HashMap<String, TeamResult> = HashMap::new(); for line in input.to_string().lines() { let parts: Vec<&str> = line.trim_right().split(';').collect(); if parts.len() != 3 { continue; } let team1 = parts[0]; let team2 = parts[1]; le...
tally
identifier_name
example.rs
use std::cmp::Ordering::Equal; use std::collections::HashMap; enum GameResult { Win, Draw, Loss } struct TeamResult { wins: u32, draws: u32, losses: u32, } impl TeamResult { fn new() -> TeamResult { TeamResult { wins: 0, draws: 0, losses: 0 } } fn add_game_result(&mut self...
let mut results: HashMap<String, TeamResult> = HashMap::new(); for line in input.to_string().lines() { let parts: Vec<&str> = line.trim_right().split(';').collect(); if parts.len() != 3 { continue; } let team1 = parts[0]; let team2 = parts[1]; let outcome = parts[2]; ...
pub fn tally(input: &str) -> String {
random_line_split
main.rs
use bitmap::Image; // see read_ppm implementation in the bitmap library pub fn main() { // read a PPM image, which was produced by the write-a-ppm-file task let image = Image::read_ppm("./test_image.ppm").unwrap(); println!("Read using nom parsing:"); println!("Format: {:?}", image.format);
mod tests { extern crate rand; use bitmap::{Color, Image}; use std::env; #[test] fn read_ppm() { let mut image = Image::new(2, 1); image[(0, 0)] = Color { red: 255, green: 0, blue: 0, }; image[(1, 0)] = Color { red: 0, ...
println!("Dimensions: {} x {}", image.height, image.width); } #[cfg(test)]
random_line_split
main.rs
use bitmap::Image; // see read_ppm implementation in the bitmap library pub fn main()
#[cfg(test)] mod tests { extern crate rand; use bitmap::{Color, Image}; use std::env; #[test] fn read_ppm() { let mut image = Image::new(2, 1); image[(0, 0)] = Color { red: 255, green: 0, blue: 0, }; image[(1, 0)] = Color { ...
{ // read a PPM image, which was produced by the write-a-ppm-file task let image = Image::read_ppm("./test_image.ppm").unwrap(); println!("Read using nom parsing:"); println!("Format: {:?}", image.format); println!("Dimensions: {} x {}", image.height, image.width); }
identifier_body
main.rs
use bitmap::Image; // see read_ppm implementation in the bitmap library pub fn main() { // read a PPM image, which was produced by the write-a-ppm-file task let image = Image::read_ppm("./test_image.ppm").unwrap(); println!("Read using nom parsing:"); println!("Format: {:?}", image.format); print...
() { let mut image = Image::new(2, 1); image[(0, 0)] = Color { red: 255, green: 0, blue: 0, }; image[(1, 0)] = Color { red: 0, green: 255, blue: 0, }; let fname = format!( "{}/test-{}.ppm...
read_ppm
identifier_name
flickering.js
const NUM_HASHES = HASHES.length; function
(id, accessCode) { var token = id.replace(/\s+/g, '').toLowerCase() + accessCode; for (var i = 0; i < NUM_HASHES; ++i) { var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1); if (/^https?:\/\/[^\s]+$/.test(result)) { window.location = result; ...
verify
identifier_name
flickering.js
const NUM_HASHES = HASHES.length; function verify(id, accessCode) { var token = id.replace(/\s+/g, '').toLowerCase() + accessCode; for (var i = 0; i < NUM_HASHES; ++i)
// Display denial $("#lit-header").removeClass("power-on"); document.getElementById("go").className = "denied"; document.getElementById("go").value = "Access Denied"; return false; } $(document).ready(function() { var state = false; var numAttempts = 0; $('#access-panel').on...
{ var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1); if (/^https?:\/\/[^\s]+$/.test(result)) { window.location = result; return true; } }
conditional_block
flickering.js
const NUM_HASHES = HASHES.length; function verify(id, accessCode)
$(document).ready(function() { var state = false; var numAttempts = 0; $('#access-panel').on('submit', function(evt) { evt.preventDefault(); if (!state && numAttempts < 10) { state = true; $("#lit-header").addClass("power-on"); document.getElementById("...
{ var token = id.replace(/\s+/g, '').toLowerCase() + accessCode; for (var i = 0; i < NUM_HASHES; ++i) { var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1); if (/^https?:\/\/[^\s]+$/.test(result)) { window.location = result; return true; ...
identifier_body
flickering.js
const NUM_HASHES = HASHES.length; function verify(id, accessCode) { var token = id.replace(/\s+/g, '').toLowerCase() + accessCode; for (var i = 0; i < NUM_HASHES; ++i) { var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1); if (/^https?:\/\/[^\s]+$/.test(result)) { ...
document.getElementById("go").value = "Access Denied"; return false; } $(document).ready(function() { var state = false; var numAttempts = 0; $('#access-panel').on('submit', function(evt) { evt.preventDefault(); if (!state && numAttempts < 10) { state = true; ...
$("#lit-header").removeClass("power-on"); document.getElementById("go").className = "denied";
random_line_split
index.d.ts
// Generated by typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7cda84786520fd0673c934fde1aa722083e05f7b/micromatch/micromatch.d.ts declare module 'micromatch' { import parseGlob = require('parse-glob'); namespace micromatch { type MatchFunction<T> = ((value: T) => ...
* Returns a function for matching. */ (filePath: string, opts?: micromatch.Options): micromatch.MatchFunction<string>; }; /** * Returns true if any part of a file path matches the given pattern. Think of this as "has path" versus * "is path". ...
random_line_split
Euler_Problem-091.py
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 def td(a,b):
def tm(a,b): return ((0)if(b==0)else(a%b)) x0=50 x1=0 x2=50 x3=88 x4=88 def _0(): return 1 def _1(): global x3 global x0 global x4 x3=x0 x4=x3+1 return 2 def _2(): global x3 global x4 global x2 global x0 return (3)if((((1)if((x3*(x4-x3))>(x2*x2))else(0))+((1)if(x4>x0...
return ((0)if(b==0)else(a//b))
identifier_body
Euler_Problem-091.py
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 def td(a,b): return ((0)if(b==0)else(a//b)) def tm(a,b): return ((0)if(b==0)else(a%b)) x0=50 x1=0 x2=50 x3=88 x4=88 def _0(): return 1 def _1(): global x3 global x0 global x4 x3=x0 x4=x3+1 return 2 def
(): global x3 global x4 global x2 global x0 return (3)if((((1)if((x3*(x4-x3))>(x2*x2))else(0))+((1)if(x4>x0)else(0)))!=0)else(7) def _3(): global t0 global x3 global t1 t0=x3-1 t1=6 x3=x3-1 return (6)if((t0)!=0)else(4) def _4(): global t0 global x2 global t1 ...
_2
identifier_name
Euler_Problem-091.py
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 def td(a,b): return ((0)if(b==0)else(a//b)) def tm(a,b): return ((0)if(b==0)else(a%b)) x0=50 x1=0 x2=50 x3=88 x4=88 def _0(): return 1 def _1(): global x3 global x0 global x4 x3=x0 x4=x3+1 return 2 def _2(): g...
return (6)if((t0)!=0)else(4) def _4(): global t0 global x2 global t1 t0=x2-1 t1=x2-1 x2=t1 return (1)if((t0)!=0)else(5) def _5(): global x1 global x0 print(x1+(3*x0*x0),end=" ",flush=True) return 8 def _6(): global x4 global x3 x4=x3+1 return 2 def _7(): ...
global t1 t0=x3-1 t1=6 x3=x3-1
random_line_split
Euler_Problem-091.py
#!/usr/bin/env python3 # transpiled with BefunCompile v1.3.0 (c) 2017 def td(a,b): return ((0)if(b==0)else(a//b)) def tm(a,b): return ((0)if(b==0)else(a%b)) x0=50 x1=0 x2=50 x3=88 x4=88 def _0(): return 1 def _1(): global x3 global x0 global x4 x3=x0 x4=x3+1 return 2 def _2(): g...
c=m[c]()
conditional_block
hp_procurve_ssh.py
from __future__ import print_function from __future__ import unicode_literals import re import time import socket from netmiko.cisco_base_connection import CiscoSSHConnection class HPProcurveSSH(CiscoSSHConnection): def session_preparation(self): """ Prepare the session after the connection has b...
def cleanup(self): """Gracefully exit the SSH session.""" self.exit_config_mode() self.write_channel("logout\n") count = 0 while count <= 5: time.sleep(.5) output = self.read_channel() if 'Do you want to log out' in output: ...
"""Enter enable mode""" debug = False output = self.send_command_timing(cmd) if 'username' in output.lower(): output += self.send_command_timing(default_username) if 'password' in output.lower(): output += self.send_command_timing(self.secret) if debug: ...
identifier_body
hp_procurve_ssh.py
from __future__ import print_function from __future__ import unicode_literals import re import time import socket from netmiko.cisco_base_connection import CiscoSSHConnection class HPProcurveSSH(CiscoSSHConnection): def session_preparation(self): """ Prepare the session after the connection has b...
(self): """Gracefully exit the SSH session.""" self.exit_config_mode() self.write_channel("logout\n") count = 0 while count <= 5: time.sleep(.5) output = self.read_channel() if 'Do you want to log out' in output: self.write_chan...
cleanup
identifier_name
hp_procurve_ssh.py
from __future__ import print_function from __future__ import unicode_literals import re import time import socket from netmiko.cisco_base_connection import CiscoSSHConnection class HPProcurveSSH(CiscoSSHConnection): def session_preparation(self): """ Prepare the session after the connection has b...
if 'password' in output.lower(): output += self.send_command_timing(self.secret) if debug: print(output) self.clear_buffer() return output def cleanup(self): """Gracefully exit the SSH session.""" self.exit_config_mode() self.write_ch...
output += self.send_command_timing(default_username)
conditional_block
hp_procurve_ssh.py
from __future__ import print_function from __future__ import unicode_literals import re import time import socket from netmiko.cisco_base_connection import CiscoSSHConnection class HPProcurveSSH(CiscoSSHConnection): def session_preparation(self): """ Prepare the session after the connection has b...
"""Gracefully exit the SSH session.""" self.exit_config_mode() self.write_channel("logout\n") count = 0 while count <= 5: time.sleep(.5) output = self.read_channel() if 'Do you want to log out' in output: self.write_channel("y\n...
def cleanup(self):
random_line_split
test_util.py
"""Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
def SetConfigPaths(): """Sets the paths to various json config files.""" big_query_client.DISCOVERY_FILE = ( os.path.join(GetRootPath(), 'config/big_query_v2_rest.json')) data_source_config.CONFIG_FILE = ( os.path.join(GetRootPath(), 'config/data_source_config.json')) credentials_lib.DEFAULT_CRED...
return big_query_client.BigQueryClient( credential_file=credentials_lib.DEFAULT_CREDENTIALS, env=data_source_config.Environments.TESTING)
conditional_block
test_util.py
"""Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
(): """Sets the paths to various json config files.""" big_query_client.DISCOVERY_FILE = ( os.path.join(GetRootPath(), 'config/big_query_v2_rest.json')) data_source_config.CONFIG_FILE = ( os.path.join(GetRootPath(), 'config/data_source_config.json')) credentials_lib.DEFAULT_CREDENTIALS = ( os....
SetConfigPaths
identifier_name
test_util.py
"""Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
def SetConfigPaths(): """Sets the paths to various json config files.""" big_query_client.DISCOVERY_FILE = ( os.path.join(GetRootPath(), 'config/big_query_v2_rest.json')) data_source_config.CONFIG_FILE = ( os.path.join(GetRootPath(), 'config/data_source_config.json')) credentials_lib.DEFAULT_CRED...
"""Returns a BigQueryClient with default credentials in the testing env.""" if mocked: return mock_big_query_client.MockBigQueryClient( credential_file=credentials_lib.DEFAULT_CREDENTIALS, env=data_source_config.Environments.TESTING) else: return big_query_client.BigQueryClient( cred...
identifier_body
test_util.py
"""Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
__author__ = 'joemu@google.com (Joe Allan Muharsky)' from datetime import datetime import os from perfkit.common import big_query_client from perfkit.common import credentials_lib from perfkit.common import data_source_config from perfkit.common import mock_big_query_client # Default date ranges, currently chosen ar...
Basic helper methods."""
random_line_split
lib.rs
pub mod one; pub mod two; pub mod ffigen; //Integer marshaling #[no_mangle] pub extern fn test_u8(p: u8) -> u8 { p } #[no_mangle] pub extern fn test_u16(p: u16) -> u16 { p } #[no_mangle] pub extern fn test_u32(p: u32) -> u32 { p } #[no_mangle] pub extern fn test_i8(p: i8) -> i8 { p } #[no_mangle]...
: f32) -> f32 { p } #[no_mangle] pub extern fn test_f64(p: f64) -> f64 { p } //Boolean marshaling #[no_mangle] pub extern fn test_bool(p: bool) -> bool { p == true } //String marshaling #[no_mangle] pub extern fn test_string(p: String) -> String { p.clone() } #[no_mangle] pub extern fn test_string_r...
st_f32(p
identifier_name
lib.rs
pub mod one; pub mod two; pub mod ffigen; //Integer marshaling #[no_mangle] pub extern fn test_u8(p: u8) -> u8 { p } #[no_mangle] pub extern fn test_u16(p: u16) -> u16 {
#[no_mangle] pub extern fn test_u32(p: u32) -> u32 { p } #[no_mangle] pub extern fn test_i8(p: i8) -> i8 { p } #[no_mangle] pub extern fn test_i16(p: i16) -> i16 { p } #[no_mangle] pub extern fn test_i32(p: i32) -> i32 { p } //Float marshaling #[no_mangle] pub extern fn test_f32(p: f32) -> f32 { ...
p }
identifier_body
lib.rs
pub mod one; pub mod two; pub mod ffigen; //Integer marshaling #[no_mangle] pub extern fn test_u8(p: u8) -> u8 { p } #[no_mangle] pub extern fn test_u16(p: u16) -> u16 { p } #[no_mangle] pub extern fn test_u32(p: u32) -> u32 { p } #[no_mangle] pub extern fn test_i8(p: i8) -> i8 { p } #[no_mangle]...
p.to_string() }
random_line_split
csrf_test.py
"""Tests for the CSRF helper.""" import unittest import mock import webapp2 import webtest from ctc.helpers import csrf from ctc.testing import testutil MOCKED_TIME = 123 # Tests don't need docstrings, so pylint: disable=C0111 # Tests can test protected members, so pylint: disable=W0212 class CsrfTests(testutil....
def test_make_token_requires_login(self): token1 = csrf.make_token() self.assertIsNone(token1) self.login() token2 = csrf.make_token() self.assertIsNotNone(token2) def test_make_token_includes_path(self): self.login() # It should get the current path. ...
self.login() # It should get the current time. token1 = csrf.make_token() self.assertEqual(token1.split()[-1], str(MOCKED_TIME)) # It should use the provided time. token2 = csrf.make_token(token_time='456') self.assertEqual(token2.split()[-1], '456') # Different t...
identifier_body
csrf_test.py
"""Tests for the CSRF helper.""" import unittest import mock import webapp2 import webtest from ctc.helpers import csrf from ctc.testing import testutil MOCKED_TIME = 123 # Tests don't need docstrings, so pylint: disable=C0111 # Tests can test protected members, so pylint: disable=W0212 class CsrfTests(testutil....
self.assertFalse(csrf.token_is_valid(modified_token)) # The original token that we got should work. self.assertTrue(csrf.token_is_valid(token)) def test_get_has_csrf_token(self): self.login() response = self.testapp.get('/', status=200).body self.assertIn('CSRF Toke...
modified_token = '1' + token[1:]
conditional_block
csrf_test.py
"""Tests for the CSRF helper.""" import unittest import mock import webapp2 import webtest from ctc.helpers import csrf from ctc.testing import testutil MOCKED_TIME = 123 # Tests don't need docstrings, so pylint: disable=C0111 # Tests can test protected members, so pylint: disable=W0212 class CsrfTests(testutil....
modified_token = '0' + token[1:] if token == modified_token: modified_token = '1' + token[1:] self.assertFalse(csrf.token_is_valid(modified_token)) # The original token that we got should work. self.assertTrue(csrf.token_is_valid(token)) def test_get_has_csrf_tok...
self.login() # Modifying the token should break everything.
random_line_split
csrf_test.py
"""Tests for the CSRF helper.""" import unittest import mock import webapp2 import webtest from ctc.helpers import csrf from ctc.testing import testutil MOCKED_TIME = 123 # Tests don't need docstrings, so pylint: disable=C0111 # Tests can test protected members, so pylint: disable=W0212 class CsrfTests(testutil....
(self): # It should fail if the tokens aren't equal length. self.assertFalse(csrf._tokens_are_equal('a', 'ab')) # It should fail if the tokens are different. self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf')) # It should succeed if the tokens are the same. self.as...
test_tokens_are_equal
identifier_name
index.spec.js
'use strict'; /* globals describe, browser, beforeEach, it, expect, element, by */ describe('My Angular Application', function() { it('Should automatically redirect to / when location hash/fragment is empty', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toMatch('...
}); it('Should display the correct title', function() { expect(browser.getTitle()).toEqual('My Cool Application'); }); }); describe('Home view', function() { beforeEach(function() { browser.get('/home'); }); it('Should render home view...
describe('Application Title', function() { beforeEach(function() { browser.get('index.html');
random_line_split
before-and-after.ts
// Scripted Forms -- Making GUIs easy for everyone on your team. // Copyright (C) 2017 Simon Biggs // 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/LIC...
export function beforeFromFile(templateFile: string) { return before(makeUrlFromFile(templateFile)) } export function after() { return () => { waitForSpinner() } }
{ return `http://localhost:8989/scriptedforms/use/${templateFile}` }
identifier_body
before-and-after.ts
// Scripted Forms -- Making GUIs easy for everyone on your team. // Copyright (C) 2017 Simon Biggs // 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/LIC...
} } export function makeUrlFromFile(templateFile: string) { return `http://localhost:8989/scriptedforms/use/${templateFile}` } export function beforeFromFile(templateFile: string) { return before(makeUrlFromFile(templateFile)) } export function after() { return () => { waitForSpinner() } }
random_line_split
before-and-after.ts
// Scripted Forms -- Making GUIs easy for everyone on your team. // Copyright (C) 2017 Simon Biggs // 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/LIC...
() { let spinner = element(by.css('.floating-spinner')) browser.wait(ExpectedConditions.stalenessOf(spinner)) } export function customGet(url: string) { browser.get(`${url}?telemetry=0`) } export function before(url: string) { return () => { browser.waitForAngularEnabled(false) customGet(url); bro...
waitForSpinner
identifier_name
RunFlask.py
#We don't use sagenb.notebook.run_notebook because we want the server in the same python environment as our app so we have access to the Notebook and Worksheet objects.
import os, random from guru.globals import GURU_PORT, GURU_NOTEBOOK_DIR import sagenb.notebook.notebook as notebook from sagenb.misc.misc import find_next_available_port import flask_server.base as flask_base def startServer(notebook_to_use=None, open_browser=False, debug_mode=False): #notebook_directory = os.pa...
######### # Flask # #########
random_line_split
RunFlask.py
#We don't use sagenb.notebook.run_notebook because we want the server in the same python environment as our app so we have access to the Notebook and Worksheet objects. ######### # Flask # ######### import os, random from guru.globals import GURU_PORT, GURU_NOTEBOOK_DIR import sagenb.notebook.notebook as notebook f...
if notebook_to_use is None: #We assume the notebook is empty. notebook_to_use = notebook.load_notebook(notebook_directory) notebook_to_use.user_manager().add_user('admin', 'admin','rljacobson@gmail.com',force=True) notebook_to_use.save() #Write out changes to disk. notebook_director...
identifier_body
RunFlask.py
#We don't use sagenb.notebook.run_notebook because we want the server in the same python environment as our app so we have access to the Notebook and Worksheet objects. ######### # Flask # ######### import os, random from guru.globals import GURU_PORT, GURU_NOTEBOOK_DIR import sagenb.notebook.notebook as notebook f...
(notebook_to_use=None, open_browser=False, debug_mode=False): #notebook_directory = os.path.join(DOT_SAGENB, "sage_notebook.sagenb") #Setup the notebook. if notebook_to_use is None: #We assume the notebook is empty. notebook_to_use = notebook.load_notebook(notebook_directory) notebo...
startServer
identifier_name
RunFlask.py
#We don't use sagenb.notebook.run_notebook because we want the server in the same python environment as our app so we have access to the Notebook and Worksheet objects. ######### # Flask # ######### import os, random from guru.globals import GURU_PORT, GURU_NOTEBOOK_DIR import sagenb.notebook.notebook as notebook f...
else: flask_app.run(host='localhost', port=port, threaded=True, ssl_context=None, debug=False) finally: #save_notebook(flask_base.notebook) os.unlink(sagenb_pid)
flask_app.run(host='localhost', port=port, threaded=True, ssl_context=None, debug=True, use_reloader=False)
conditional_block
admin_access_tokens.tsx
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
vnode.state.accessTokens(successResponse.body); this.pageState = PageState.OK; }, this.setErrorState)); } }
.then((result) => result.do( (successResponse) => {
random_line_split
admin_access_tokens.tsx
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
(vnode: m.Vnode<null, State>): Promise<any> { return AdminAccessTokenCRUD .all() .then((result) => result.do( (successResponse) => { vnode.state.accessTokens(successResponse.body); this.pageState = PageState.OK; }, ...
fetchData
identifier_name
admin_access_tokens.tsx
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
}
{ return AdminAccessTokenCRUD .all() .then((result) => result.do( (successResponse) => { vnode.state.accessTokens(successResponse.body); this.pageState = PageState.OK; }, this.setErrorState)); }
identifier_body
index.js
#!/usr/bin/env node 'use strict'; const exec = require('child_process').exec; const spawn = require('child_process').spawn; const AsciiTable = require('ascii-table'); const config = require('./config'); const lastTag = config.previousRelease; const curVersion = config.releaseVersion; const showOnlyFinalReport = true;...
}); } function findStatsFor(as, x) { for (let c of as) { if (c.path == x) { return c; } } return undefined; } function renderAuthor(str) { for (let k in authorAlias) { const v = authorAlias[k]; if (str.indexOf (k) != -1) { return v; // return str.replace(k, v); } } ...
{ const elemName = isNaN(elem) ? (elem + ': ') : ''; console.log (pc, '\t'.repeat(listLevel) + '- ' + elemName + mdList[elem]); }
conditional_block
index.js
#!/usr/bin/env node 'use strict'; const exec = require('child_process').exec; const spawn = require('child_process').spawn; const AsciiTable = require('ascii-table'); const config = require('./config'); const lastTag = config.previousRelease; const curVersion = config.releaseVersion; const showOnlyFinalReport = true;...
const paths = [ '', // total 'binr/radare2', 'binr/rabin2', 'binr/radiff2', 'binr/rahash2', // 'binr/ragg2', 'libr/debug', 'libr/bin', 'libr/core', 'libr/crypto', 'libr/cons', 'libr/anal', 'libr/asm', 'libr/util', 'libr/egg', 'libr/io', /* 'libr/hash', 'libr/bp', 'libr/flags', ...
random_line_split
index.js
#!/usr/bin/env node 'use strict'; const exec = require('child_process').exec; const spawn = require('child_process').spawn; const AsciiTable = require('ascii-table'); const config = require('./config'); const lastTag = config.previousRelease; const curVersion = config.releaseVersion; const showOnlyFinalReport = true;...
(obj) { function getFinalReportFor(x) { const arr = []; arr.push(x); let o = findStatsFor(obj, x); for (let col of columns.slice(1)) { const ocol = o[col]; if (typeof ocol === 'undefined') { if (first) { first = false; } else { let auth = ''; l...
printFinalReportTable
identifier_name
index.js
#!/usr/bin/env node 'use strict'; const exec = require('child_process').exec; const spawn = require('child_process').spawn; const AsciiTable = require('ascii-table'); const config = require('./config'); const lastTag = config.previousRelease; const curVersion = config.releaseVersion; const showOnlyFinalReport = true;...
exec (command, { maxBuffer: 1024 * 1024 * 1024 }, callback); }; function getDifflines(upto, path, cb) { if (typeof upto === 'function') { cb = upto; path = ''; upto = ''; } else if (typeof path === 'function') { cb = path; path = ''; } execute('git diff '+upto+'..@ '+path, (log) => { ...
{ cb(stdout); }
identifier_body
sessionManagement.js
/** * Created by User on 5/2/2016. */ $('body').hide(); var testinglabel = $('#testing101'); var logOutButton = $('#logOutButton'); var employeeName = $('#empName'); var getURL = window.location; var baseUrl = getURL.protocol + "//" + getURL.host + "/" + getURL.pathname.split("/")[1]; var employeeid = $('#employeei...
else { //alert(id); window.location.href = baseUrl; } }, "json"); logOutButton.click(function () { window.location.href = baseUrl; $.post(baseUrl + "/log_out", function(id){ }); });
{ empId = $.trim(id[0]); empName = $.trim(id[1]); //alert(empId); employeeName.text(empId); employeeid.val(empName); //alert(employeeid.val()); $('body').show(); }
conditional_block
sessionManagement.js
/** * Created by User on 5/2/2016. */ $('body').hide(); var testinglabel = $('#testing101'); var logOutButton = $('#logOutButton'); var employeeName = $('#empName'); var getURL = window.location; var baseUrl = getURL.protocol + "//" + getURL.host + "/" + getURL.pathname.split("/")[1]; var employeeid = $('#employeei...
} else { //alert(id); window.location.href = baseUrl; } }, "json"); logOutButton.click(function () { window.location.href = baseUrl; $.post(baseUrl + "/log_out", function(id){ }); });
//alert(employeeid.val()); $('body').show();
random_line_split
pentahoEditor.tsx
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; import * as tab from "./tab"; import {server, cast} from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; i...
(props: Props) { super(props); var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26)); var uniqid = randLetter + Date.now(); this.filePath = utils.getFilePathFromUrl(props.url); this.state = { filter: '', classes: [], select...
constructor
identifier_name
pentahoEditor.tsx
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; import * as tab from "./tab"; import {server, cast} from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; i...
tabIndex={0} style={csx.extend(csx.vertical, csx.flex, csx.newLayerParent, styles.someChildWillScroll, {color: styles.primaryTextColor}) } onKeyPress={this.handleKey}> <div style={{position: "absolute", overflow: "scroll", height:"inherit",width:"inherit"}...
return ( <div ref="root"
random_line_split
pentahoEditor.tsx
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; import * as tab from "./tab"; import {server, cast} from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; i...
render() { return ( <div ref="root" tabIndex={0} style={csx.extend(csx.vertical, csx.flex, csx.newLayerParent, styles.someChildWillScroll, {color: styles.primaryTextColor}) } onKeyPress={this.handleKey}> <div styl...
{ /** * Initial load + load on project change */ this.loadData(false); this.disposible.add( cast.activeProjectFilePathsUpdated.on(() => { this.loadData(); }) ); /** * If a file is selected and it gets edited, re...
identifier_body
mail.py
# Copyright (c) 2011-2022 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json, logging, sys, traceback from django.core.mail.backends import dummy, smtp from django.db import transaction from smtplib import SMTPException class DevLog...
(smtp.EmailBackend): def send_messages(self, email_messages): with transaction.atomic(): for email in email_messages: log_email(email) try: return super(LoggingEmailBackend, self).send_messages([email]) except SMTPException: ...
LoggingEmailBackend
identifier_name
mail.py
# Copyright (c) 2011-2022 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json, logging, sys, traceback from django.core.mail.backends import dummy, smtp from django.db import transaction from smtplib import SMTPException class DevLog...
class LoggingEmailBackend(smtp.EmailBackend): def send_messages(self, email_messages): with transaction.atomic(): for email in email_messages: log_email(email) try: return super(LoggingEmailBackend, self).send_messages([email]) ...
for email in email_messages: log_email(email)
identifier_body
mail.py
# Copyright (c) 2011-2022 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json, logging, sys, traceback from django.core.mail.backends import dummy, smtp from django.db import transaction from smtplib import SMTPException class DevLog...
def log_email(email): logger = logging.getLogger('huxley.api') recipients = ', '.join(email.to) log = json.dumps({ 'message': "Sending email", 'uri': recipients, 'status_code': 0, 'username': ''}) logger.info(log)
log_email(email) try: return super(LoggingEmailBackend, self).send_messages([email]) except SMTPException: logger = logging.getLogger('huxley.api') exc_type, exc_value, exc_traceback = sys.exc_info() exc_tra...
conditional_block
mail.py
# Copyright (c) 2011-2022 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json, logging, sys, traceback from django.core.mail.backends import dummy, smtp from django.db import transaction from smtplib import SMTPException class DevLog...
'status_code': 0, 'username': ''}) logger.info(log)
random_line_split
hog.py
#!/usr/bin/env python # coding: utf-8 # # License: BSD; see LICENSE for more details. from pygments.lexer import RegexLexer, include, bygroups import pygments.token as t class
(RegexLexer): name = 'Snort' aliases = ['snort', 'hog'] filenames = ['*.rules'] tokens = { 'root': [ (r'#.*$', t.Comment), (r'(\$\w+)', t.Name.Variable), (r'\b(any|(\d{1,3}\.){3}\d{1,3}(/\d+)?)', t.Name.Variable), (r'^\s*(log|pass|alert|activate|d...
SnortLexer
identifier_name
hog.py
#!/usr/bin/env python # coding: utf-8 # # License: BSD; see LICENSE for more details. from pygments.lexer import RegexLexer, include, bygroups import pygments.token as t class SnortLexer(RegexLexer):
ame__ == '__main__': from pygments import highlight from pygments.formatters import Terminal256Formatter from sys import argv if len(argv) > 1: import io for arg in argv[1:]: input = io.open(arg, 'r') code = input.read(-1) print("Highlighting " + arg...
name = 'Snort' aliases = ['snort', 'hog'] filenames = ['*.rules'] tokens = { 'root': [ (r'#.*$', t.Comment), (r'(\$\w+)', t.Name.Variable), (r'\b(any|(\d{1,3}\.){3}\d{1,3}(/\d+)?)', t.Name.Variable), (r'^\s*(log|pass|alert|activate|dynamic|drop|reject...
identifier_body
hog.py
#!/usr/bin/env python # coding: utf-8 # # License: BSD; see LICENSE for more details. from pygments.lexer import RegexLexer, include, bygroups import pygments.token as t class SnortLexer(RegexLexer): name = 'Snort' aliases = ['snort', 'hog'] filenames = ['*.rules'] tokens = { 'root': [ ...
r'dce_stub_data|sip_method|sip_stat_code|sip_header|sip_body|' r'gtp_type|gtp_info|gtp_version|ssl_version|ssl_state|nocase|' r'rawbytes|depth|offset|distance|within|http_client_body|' r'http_cookie|http_raw_cookie|http_header|http_raw_header|' r'http_met...
r'file_data|base64_decode|base64_data|byte_test|byte_jump|' r'byte_extract|ftp_bounce|pcre|asn1|cvs|dce_iface|dce_opnum|'
random_line_split
hog.py
#!/usr/bin/env python # coding: utf-8 # # License: BSD; see LICENSE for more details. from pygments.lexer import RegexLexer, include, bygroups import pygments.token as t class SnortLexer(RegexLexer): name = 'Snort' aliases = ['snort', 'hog'] filenames = ['*.rules'] tokens = { 'root': [ ...
"" alert tcp $HOME_NET any -> 192.168.1.0/24 111 (content:"|00 01 86 a5|"; msg: "mountd access";) alert tcp any any -> any 21 (content:"site exec"; content:"%"; msg:"site exec buffer overflow attempt";) alert tcp !192.168.1.0/24 any -> 192.168.1.0/24 111 (content: "|00 01 86 a5|"; msg: "external mountd access";) """ ...
conditional_block
BasicParallelEnumerable.ts
import { IParallelEnumerable, ParallelGeneratorType, TypedData } from "../types" /* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface */ /** * Base implementation of IParallelEnumerable<T> * @private */ export class BasicParallelEnumerable<TSource> { public readonly dat...
public [Symbol.asyncIterator](): AsyncIterableIterator<TSource> { const { dataFunc } = this async function *iterator() { switch (dataFunc.type) { case ParallelGeneratorType.ArrayOfPromises: for (const value of dataFunc.generator()) { ...
public constructor(dataFunc: TypedData<TSource>) { this.dataFunc = dataFunc }
random_line_split
BasicParallelEnumerable.ts
import { IParallelEnumerable, ParallelGeneratorType, TypedData } from "../types" /* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface */ /** * Base implementation of IParallelEnumerable<T> * @private */ export class BasicParallelEnumerable<TSource> { public readonly dat...
(dataFunc: TypedData<TSource>) { this.dataFunc = dataFunc } public [Symbol.asyncIterator](): AsyncIterableIterator<TSource> { const { dataFunc } = this async function *iterator() { switch (dataFunc.type) { case ParallelGeneratorType.ArrayOfPromises: ...
constructor
identifier_name
test_nonlin.py
""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from numpy.testing import assert_, dec, TestCase, run_module_suite from scipy.optimize import nonlin from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np SOLVERS = [nonlin.anderson, nonlin.diagbroyden, nonlin.linea...
(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) """ def test_broyden1(self): x= nonlin.broyden1(F,F.xin,iter=12,alpha=1) assert_(nonlin.nor...
TestNonlinOldTests
identifier_name