file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
view_mixins.py
from django.apps import apps as django_apps from django.core.exceptions import ObjectDoesNotExist from django.views.generic.base import ContextMixin class SubjectOffstudyViewMixinError(Exception): pass class SubjectOffstudyViewMixin(ContextMixin): """Adds subject offstudy to the context. Declare with ...
(self): """Returns a model instance either saved or unsaved. If a save instance does not exits, returns a new unsaved instance. """ model_cls = self.subject_offstudy_model_cls try: subject_offstudy = model_cls.objects.get( subject_identifier=self.subj...
subject_offstudy
identifier_name
import-article.ts
import http = require('http'); import crypto = require('crypto'); ///<reference path="../../scripts/typings/q/Q.d.ts"/> ///<reference path="../../scripts/typings/moment/moment.d.ts"/> ///<reference path="../../scripts/typings/cheerio/cheerio.d.ts"/> import Q = require('q'); import moment = require('moment'); import ch...
constructor(articlesIndex:ArticlesIndex, documentImporter:DocumentImporter) { this.articlesIndex = articlesIndex; this.docImporter = documentImporter; } enact(request:ImportArticleRequest):ImportArticleResult { throw 'WTF'; } enactAsync(req:ImportArticleRequest):Q.Promise<...
private articlesIndex:ArticlesIndex; private docImporter:DocumentImporter;
random_line_split
import-article.ts
import http = require('http'); import crypto = require('crypto'); ///<reference path="../../scripts/typings/q/Q.d.ts"/> ///<reference path="../../scripts/typings/moment/moment.d.ts"/> ///<reference path="../../scripts/typings/cheerio/cheerio.d.ts"/> import Q = require('q'); import moment = require('moment'); import ch...
(req:ImportArticleRequest):Q.Promise<ImportArticleResult> { var _cthis = this; return this.articlesIndex.getArticleAsync(req.articleSource, req.articleId).then(function (article:Article):Q.Promise<Article> { return _cthis.docImporter.importArticleAsync(article); }).then(function (art...
enactAsync
identifier_name
import-article.ts
import http = require('http'); import crypto = require('crypto'); ///<reference path="../../scripts/typings/q/Q.d.ts"/> ///<reference path="../../scripts/typings/moment/moment.d.ts"/> ///<reference path="../../scripts/typings/cheerio/cheerio.d.ts"/> import Q = require('q'); import moment = require('moment'); import ch...
enact(request:ImportArticleRequest):ImportArticleResult { throw 'WTF'; } enactAsync(req:ImportArticleRequest):Q.Promise<ImportArticleResult> { var _cthis = this; return this.articlesIndex.getArticleAsync(req.articleSource, req.articleId).then(function (article:Article):Q.Promise<A...
{ this.articlesIndex = articlesIndex; this.docImporter = documentImporter; }
identifier_body
sync.js
post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; ...
(msfRecord, mongoRecord){ //console.log(msfRecord); var needsUpdate = false; var fieldsToUpdate = {} for(var key in msfRecord){ if(msfRecord[key] != mongoRecord[key]){ fieldsToUpdate[key] = msfRecord[key]; needsUpdate = true; } } var msfServices = Mamoru....
checkHost
identifier_name
sync.js
post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; ...
fieldsToUpdate.notes = msfNotes; } var msfVulns = Mamoru.Utils.getHostVulns(msfRecord.address) if(msfVulns){ msfVulns = msfVulns.map((vuln)=>{ delete vuln.host; return vuln; }); } if(msfVulns.length != mongoRecord.vulns.length){ needsU...
random_line_split
sync.js
post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; ...
let consolesToRemove = existingConsoles.splice(0,existingConsoles-poolSize) for(let i=0;i<consolesToRemove.length;i++){ let existsInMongo = Mamoru.Collections.Consoles.findOne({msfId:consolesToRemove[i].id}); if(existsInMongo){ Mamoru.Collections.Consoles.remove(e...
{ var poolSize = Meteor.settings.consolePoolSize //check if there are existing consoles let existingConsoles = Mamoru.Utils.listConsoles(); console.log(existingConsoles); let numExistingConsoles = existingConsoles.consoles.length console.log(`there are ${numExistingConsoles} existing consoles`);...
identifier_body
sync.js
post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; ...
if(msfServices.length != mongoRecord.services.length){ needsUpdate = true; fieldsToUpdate.services = msfServices; } var msfNotes = Mamoru.Utils.getHostNotes(msfRecord.address) if(msfNotes){ msfServices = msfNotes.map((note)=>{ delete note.host; return n...
{ msfServices = msfServices.map((service)=>{ delete service.host; return service; }); }
conditional_block
router_preloader.ts
/** *@license *Copyright Google Inc. All Rights Reserved. * *Use of this source code is governed by an MIT-style license that can be *found in the LICENSE file at https://angular.io/license */ import {Compiler, Injectable, Injector, NgModuleFactoryLoader, NgModuleRef, OnDestroy} from '@angular/core'; import {Observabl...
// TODO(issue/24571): remove '!'. private subscription !: Subscription; constructor( private router: Router, moduleLoader: NgModuleFactoryLoader, compiler: Compiler, private injector: Injector, private preloadingStrategy: PreloadingStrategy) { const onStartLoad = (r: Route) => router.triggerEvent...
* @publicApi */ @Injectable() export class RouterPreloader implements OnDestroy { private loader: RouterConfigLoader;
random_line_split
router_preloader.ts
/** *@license *Copyright Google Inc. All Rights Reserved. * *Use of this source code is governed by an MIT-style license that can be *found in the LICENSE file at https://angular.io/license */ import {Compiler, Injectable, Injector, NgModuleFactoryLoader, NgModuleRef, OnDestroy} from '@angular/core'; import {Observabl...
( private router: Router, moduleLoader: NgModuleFactoryLoader, compiler: Compiler, private injector: Injector, private preloadingStrategy: PreloadingStrategy) { const onStartLoad = (r: Route) => router.triggerEvent(new RouteConfigLoadStart(r)); const onEndLoad = (r: Route) => router.triggerEvent(new...
constructor
identifier_name
batch.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; extern crate num;
struct Pair { key: String, value: String, } fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared, CassError> { unsafe { let query = "INSERT INTO examples.pairs (key, value) VALUES (?, ?)"; let future = &mut *cass_session_prepare(session, CString::new(quer...
mod examples_util; use examples_util::*; use std::ffi::CString; use cassandra_sys::*;
random_line_split
batch.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; extern crate num; mod examples_util; use examples_util::*; use std::ffi::CString; use cassandra_sys::*; struct
{ key: String, value: String, } fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared, CassError> { unsafe { let query = "INSERT INTO examples.pairs (key, value) VALUES (?, ?)"; let future = &mut *cass_session_prepare(session, CString::new(query).unwrap()....
Pair
identifier_name
batch.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; extern crate num; mod examples_util; use examples_util::*; use std::ffi::CString; use cassandra_sys::*; struct Pair { key: String, value: String, } fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared,...
} fn insert_into_batch_with_prepared(session: &mut CassSession, prepared: &CassPrepared, pairs: Vec<Pair>) -> Result<(), CassError> { unsafe { let batch = cass_batch_new(CASS_BATCH_TYPE_LOGGED); for pair in pairs { let statement = cass_prepared_bind(...
{ unsafe { let query = "INSERT INTO examples.pairs (key, value) VALUES (?, ?)"; let future = &mut *cass_session_prepare(session, CString::new(query).unwrap().as_ptr()); cass_future_wait(future); let rc = cass_future_error_code(future); let result = match rc { CAS...
identifier_body
batch.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; extern crate num; mod examples_util; use examples_util::*; use std::ffi::CString; use cassandra_sys::*; struct Pair { key: String, value: String, } fn prepare_insert_into_batch<'a>(session: &mut CassSession) -> Result<&'a CassPrepared,...
_ => { print_error(future); Err(rc) } }; cass_future_free(future); result } } fn insert_into_batch_with_prepared(session: &mut CassSession, prepared: &CassPrepared, pairs: Vec<Pair>) -> Result<(), Ca...
{ let prepared = &*cass_future_get_prepared(future); Ok(prepared) }
conditional_block
wp-mediaelement.js
/* global mejs, _wpmejsSettings */ (function( window, $ ) { window.wp = window.wp || {}; // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma'); function wpMediaElement() { var setting...
settings.success = settings.success || function (mejs) { var autoplay, loop; if ( 'flash' === mejs.pluginType ) { autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes.autoplay; loop = mejs.attributes.loop && 'false' !== mejs.attributes.loop; autoplay && mejs.addEvent...
{ settings = $.extend( true, {}, _wpmejsSettings ); }
conditional_block
wp-mediaelement.js
/* global mejs, _wpmejsSettings */ (function( window, $ ) { window.wp = window.wp || {}; // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma');
function wpMediaElement() { var settings = {}; /** * Initialize media elements. * * Ensures media elements that have already been initialized won't be * processed again. * * @since 4.4.0 */ function initialize() { if ( typeof _wpmejsSettings !== 'undefined' ) { settings ...
random_line_split
wp-mediaelement.js
/* global mejs, _wpmejsSettings */ (function( window, $ ) { window.wp = window.wp || {}; // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma'); function wpMediaElement() { var setting...
() { if ( typeof _wpmejsSettings !== 'undefined' ) { settings = $.extend( true, {}, _wpmejsSettings ); } settings.success = settings.success || function (mejs) { var autoplay, loop; if ( 'flash' === mejs.pluginType ) { autoplay = mejs.attributes.autoplay && 'false' !== mejs.attribut...
initialize
identifier_name
wp-mediaelement.js
/* global mejs, _wpmejsSettings */ (function( window, $ ) { window.wp = window.wp || {}; // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma'); function wpMediaElement() { var setting...
}; // Only initialize new media elements. $( '.wp-audio-shortcode, .wp-video-shortcode' ) .not( '.mejs-container' ) .filter(function () { return ! $( this ).parent().hasClass( '.mejs-mediaelement' ); }) .mediaelementplayer( settings ); } return { initialize: initializ...
{ if ( typeof _wpmejsSettings !== 'undefined' ) { settings = $.extend( true, {}, _wpmejsSettings ); } settings.success = settings.success || function (mejs) { var autoplay, loop; if ( 'flash' === mejs.pluginType ) { autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes....
identifier_body
project.ts
) => any | void) { return readFile(filePath) .then(tsConfigJson => { const tsConfig = JSON.parse(tsConfigJson); const result = fn(tsConfig) || tsConfig; return writeFile(filePath, JSON.stringify(result, null, 2)); }); } export function updateTsConfig(fn: (json: any) => any | void) { ret...
'e2e', ); await useCIChrome( '', ); // legacy projects await useCIChrome( 'src', ); if (argv['ng-snapshots'] || argv['ng-tag']) { await useSha(); } await writeFile('.npmrc', 'registry=http://localhost:4873'); console.log( `Project ${name} created... Installing npm.`, ); a...
{ const argv: string[] = getGlobalVariable('argv'); await git( 'config', 'user.email', 'angular-core+e2e@google.com', ); await git( 'config', 'user.name', 'Angular CLI E2e', ); await git( 'config', 'commit.gpgSign', 'false', ); await useCIChrome(
identifier_body
project.ts
=> any | void) { return readFile(filePath) .then(tsConfigJson => { const tsConfig = JSON.parse(tsConfigJson); const result = fn(tsConfig) || tsConfig; return writeFile(filePath, JSON.stringify(result, null, 2)); }); } export function updateTsConfig(fn: (json: any) => any | void) { retu...
if (label) { json[key][`@angular/${pkgName}`] = `github:angular/${pkgName}-builds${label}`; } else { const replacement = ngSnapshotVersions.dependencies[`@angular/${pkgName}`]; if (!replacement) { missingSnapshots.push(`m...
{ return; }
conditional_block
project.ts
) => any | void) { return readFile(filePath) .then(tsConfigJson => { const tsConfig = JSON.parse(tsConfigJson); const result = fn(tsConfig) || tsConfig; return writeFile(filePath, JSON.stringify(result, null, 2)); }); } export function updateTsConfig(fn: (json: any) => any | void) { ret...
// legacy project structure const e2eProject = workspaceJson.projects[projectName + '-e2e']; if (e2eProject) { const e2eTargets = e2eProject.targets || e2eProject.architect; e2eTargets.e2e.options.webdriverUpdate = false; } }) .then(() => updateJsonFile('package.json', json => { ...
appTargets.e2e.options.webdriverUpdate = false; }
random_line_split
project.ts
Ivy the i18n extraction uses VE. await updateJsonFile('tsconfig.json', config => { config.angularCompilerOptions.disableTypeScriptVersionCheck = true; }); } await prepareProjectForE2e(name); } export async function prepareProjectForE2e(name) { const argv: string[] = getGlobalVariable('argv'); ...
isPrereleaseCli
identifier_name
index.d.ts
// Type definitions for webpack-serve 2.0 // Project: https://github.com/shellscape/webpack-serve // Definitions by: Ryan Clark <https://github.com/rynclark> // Jokcy <https://github.com/Jokcy> // ZSkycat <https://github.com/ZSkycat> // Definitions: https://github.com/DefinitelyTyped/Def...
/** Name of the browser to open */ app?: string; /** Path on the server to open */ path?: string; } type OnOptions = { [K in keyof EventMap]?: (args: EventMap[K]) => void }; interface InitializedKoa extends koa { server: net.Server; stop: () => void; } ...
interface OpenOptions {
random_line_split
zip.py
"""SCons.Tool.zip Tool-specific initialization for zip. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon...
(env): return internal_zip or env.Detect('zip') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
exists
identifier_name
zip.py
"""SCons.Tool.zip Tool-specific initialization for zip. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon...
zipAction = SCons.Action.Action(zip, varlist=['ZIPCOMPRESSION']) ZipBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$ZIPCOM', '$ZIPCOMSTR'), source_factory = SCons.Node.FS.Entry, source_scanner = SCons.Defaults.DirScanner, ...
random_line_split
zip.py
"""SCons.Tool.zip Tool-specific initialization for zip. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon...
def exists(env): return internal_zip or env.Detect('zip') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
"""Add Builders and construction variables for zip to an Environment.""" try: bld = env['BUILDERS']['Zip'] except KeyError: bld = ZipBuilder env['BUILDERS']['Zip'] = bld env['ZIP'] = 'zip' env['ZIPFLAGS'] = SCons.Util.CLVar('') env['ZIPCOM'] = zipAction env[...
identifier_body
zip.py
"""SCons.Tool.zip Tool-specific initialization for zip. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon...
zf.close() else: zipcompression = 0 zip = "$ZIP $ZIPFLAGS ${TARGET.abspath} $SOURCES" zipAction = SCons.Action.Action(zip, varlist=['ZIPCOMPRESSION']) ZipBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$ZIPCOM', '$ZIPCOMSTR'), source_factory = SCons.N...
zf.write(str(s))
conditional_block
arg_visitor.rs
use std::io::{Read, Take}; use std::vec; use serde::de; use serde::de::{DeserializeSeed, SeqAccess, Visitor}; use error::{Error, ResultE}; use super::osc_reader::OscReader; use super::osc_type::OscType; use super::maybe_skip_comma::MaybeSkipComma; #[derive(Debug)] pub struct ArgDeserializer<'a, R: Read + 'a> { da...
<'a, R: Read + 'a> { read: &'a mut Take<R>, /// calling .next() on this returns the OSC char code of the next argument, /// e.g. 'i' for i32, 'f' for f32, etc. /// We store this as an iterator to avoid tracking the index of the current arg. arg_types : MaybeSkipComma<vec::IntoIter<u8>>, } impl<'a, ...
ArgVisitor
identifier_name
arg_visitor.rs
use std::io::{Read, Take}; use std::vec; use serde::de; use serde::de::{DeserializeSeed, SeqAccess, Visitor}; use error::{Error, ResultE}; use super::osc_reader::OscReader; use super::osc_type::OscType; use super::maybe_skip_comma::MaybeSkipComma; #[derive(Debug)] pub struct ArgDeserializer<'a, R: Read + 'a> { da...
} fn parse_arg(&mut self, typecode: u8) -> ResultE<OscType> { match typecode { b'i' => self.read.parse_i32().map(|i| { OscType::I32(i) }), b'f' => self.read.parse_f32().map(|f| { OscType::F32(f) }), b's' => self.read.parse_str().map(|s| { OscType::String(s) }), ...
fn parse_next(&mut self) -> ResultE<Option<OscType>> { match self.arg_types.next() { None => Ok(None), Some(tag) => self.parse_arg(tag).map(|arg| Some(arg)), }
random_line_split
MaskLayer.js
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2014 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with th...
}; } });
{ me.constrainTo = me.calculateConstrainRegion(); }
conditional_block
MaskLayer.js
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2014 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with th...
this.dd.onStart = function (e) { var me = this, comp = me.comp; // Cache the start [X, Y] array this.startPosition = comp.getPosition(true); // If client Component has a ghost method to show a lightweight version of itself // ...
this.callParent(arguments);
random_line_split
build.rs
#[cfg(not(feature = "unstable"))] mod inner { extern crate syntex; extern crate diesel_codegen; extern crate dotenv_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let mut registry = syntex::Registry::new(); die...
fn main() { dotenv().ok(); let database_url = ::std::env::var("DATABASE_URL") .expect("DATABASE_URL must be set to run tests"); let connection = Connection::establish(&database_url).unwrap(); migrations::run_pending_migrations(&connection).unwrap(); inner::main(); }
extern crate dotenv; use diesel::*; use dotenv::dotenv;
random_line_split
build.rs
#[cfg(not(feature = "unstable"))] mod inner { extern crate syntex; extern crate diesel_codegen; extern crate dotenv_codegen; use std::env; use std::path::Path; pub fn main()
} #[cfg(feature = "unstable")] mod inner { pub fn main() {} } extern crate diesel; extern crate dotenv; use diesel::*; use dotenv::dotenv; fn main() { dotenv().ok(); let database_url = ::std::env::var("DATABASE_URL") .expect("DATABASE_URL must be set to run tests"); let connection = Connecti...
{ let out_dir = env::var_os("OUT_DIR").unwrap(); let mut registry = syntex::Registry::new(); diesel_codegen::register(&mut registry); dotenv_codegen::register(&mut registry); let src = Path::new("tests/lib.in.rs"); let dst = Path::new(&out_dir).join("lib.rs"); r...
identifier_body
build.rs
#[cfg(not(feature = "unstable"))] mod inner { extern crate syntex; extern crate diesel_codegen; extern crate dotenv_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let mut registry = syntex::Registry::new(); die...
() {} } extern crate diesel; extern crate dotenv; use diesel::*; use dotenv::dotenv; fn main() { dotenv().ok(); let database_url = ::std::env::var("DATABASE_URL") .expect("DATABASE_URL must be set to run tests"); let connection = Connection::establish(&database_url).unwrap(); migrations::run_p...
main
identifier_name
test_operations.py
"""Brief description of what this file should test""" import pytest from Calculator import operations def test_addition(): assert operations.add(1, 2) == 3 def test_subtraction(): assert operations.subtract(1 ,2) == -1 def test_multiplication(): assert operations.multiply(2, -1) == -2 def test_divide...
(given, expected): assert operations.ceiling(given) == expected @pytest.mark.parametrize("given_a, given_b, expected", [ (0, 1, 0), (3, 3, 27), (-3, 0, 1), (0, 0, 1), ]) def test_power(given_a, given_b, expected): assert operations.power(given_a, given_b) == expected @pytest.mark.parametrize("...
test_ceiling
identifier_name
test_operations.py
"""Brief description of what this file should test""" import pytest from Calculator import operations def test_addition(): assert operations.add(1, 2) == 3 def test_subtraction(): assert operations.subtract(1 ,2) == -1 def test_multiplication(): assert operations.multiply(2, -1) == -2 def test_divide...
@pytest.mark.parametrize("given, expected", [ (0, 0), (-1.5, -1), (2.3, 3), ]) def test_ceiling(given, expected): assert operations.ceiling(given) == expected @pytest.mark.parametrize("given_a, given_b, expected", [ (0, 1, 0), (3, 3, 27), (-3, 0, 1), (0, 0, 1), ]) def test_power(given_a...
random_line_split
test_operations.py
"""Brief description of what this file should test""" import pytest from Calculator import operations def test_addition(): assert operations.add(1, 2) == 3 def test_subtraction(): assert operations.subtract(1 ,2) == -1 def test_multiplication(): assert operations.multiply(2, -1) == -2 def test_divide...
@pytest.mark.parametrize("given, expected", [ (0, 0), (-1.5, -1), (2.3, 3), ]) def test_ceiling(given, expected): assert operations.ceiling(given) == expected @pytest.mark.parametrize("given_a, given_b, expected", [ (0, 1, 0), (3, 3, 27), (-3, 0, 1), (0, 0, 1), ]) def test_power(given...
assert operations.floor(given) == expected
identifier_body
behavior_binary_table.py
selected_observations (list): list of selected observations parameters_obs (dict): dcit of parameters time_interval (float): time interval (in seconds) Returns: dict: dictionary of tablib dataset """ results_df = {} state_behavior_codes = [ x for x in utiliti...
file_name_with_subject = str(os.path.splitext(file_name)[0] + utilities.safeFileName("_" + subject)) + "." + output_format
random_line_split
behavior_binary_table.py
02110-1301, USA. """ import os import pathlib import re import sys from decimal import Decimal as dc import tablib from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QFileDialog, QInputDialog, QMessageBox) from boris import dialog from boris import project_functions from boris import select_observations from ...
x for x in utilities.point_behavior_codes(pj[ETHOGRAM]) if x in parameters_obs[SELECTED_BEHAVIORS] ] if not state_behavior_codes and not point_behavior_codes: return {"error": True, "msg": "No state events selected"} for obs_id in selected_observations: start_time = parameters_obs[...
""" create behavior binary table Args: pj (dict): project dictionary selected_observations (list): list of selected observations parameters_obs (dict): dcit of parameters time_interval (float): time interval (in seconds) Returns: dict: dictionary of tablib dataset ...
identifier_body
behavior_binary_table.py
02110-1301, USA. """ import os import pathlib import re import sys from decimal import Decimal as dc import tablib from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QFileDialog, QInputDialog, QMessageBox) from boris import dialog from boris import project_functions from boris import select_observations from ...
(pj: dict): """ ask user for parameters for behavior binary table call create_behavior_binary_table """ _, selected_observations = select_observations.select_observations( pj, MULTIPLE, "Select observations for the behavior binary table") if not selected_observations: return ...
behavior_binary_table
identifier_name
behavior_binary_table.py
02110-1301, USA. """ import os import pathlib import re import sys from decimal import Decimal as dc import tablib from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QFileDialog, QInputDialog, QMessageBox) from boris import dialog from boris import project_functions from boris import select_observations from ...
time_interval = utilities.float2decimal(i) results_df = create_behavior_binary_table(pj, selected_observations, parameters, time_interval) if "error" in results_df: QMessageBox.warning(None, programName, results_df["msg"]) return # save results if len(selected_observations) == 1:...
return
conditional_block
functions_8.js
var searchData= [ ['trackadvertiserid',['trackAdvertiserID',['../interfacei_omniata_a_p_i.html#a45b87869378da3b3eecb262747fc2e9d',1,'iOmniataAPI']]], ['trackadvertiseridwithparameters_3a',['trackAdvertiserIDwithParameters:',['../interfacei_omniata_a_p_i.html#af718ede70174276c4a8a1b1d16926a0e',1,'iOmniataAPI']]], ...
];
['trackpurchaseevent_3acurrency_5fcode_3aadditional_5fparams_3a',['trackPurchaseEvent:currency_code:additional_params:',['../interfacei_omniata_a_p_i.html#a6dadc753626a82185efa43045fdc1e46',1,'iOmniataAPI']]], ['trackpushnotification_3a',['trackPushNotification:',['../interfacei_omniata_a_p_i.html#afbabb3ec83785a82...
random_line_split
create_plants2table.py
#!/usr/bin/python import os import sys import math import glob import sql import process_xls as p_xls """ Change to whatever is needed. """ DEFAULT_DATE_STR = '' DB_NAME = 'trost_prod' TABLE_NAME = 'plants2' TABLE = [ 'id INT(11) AUTO_INCREMENT', 'aliquot INT(11)', 'name VARCHAR(45)', 'subspecies_...
""" Table writing logic is specific to this table, therefore it does not use sql.write_sql_table. """ for row in sql.prepare_sql_table(data, columns_d): # print row try: """ This adds the required values for subspecies.limsid and lo...
dobj.Subspecies_Id = -1
conditional_block
create_plants2table.py
#!/usr/bin/python import os import sys import math import glob import sql import process_xls as p_xls """ Change to whatever is needed. """ DEFAULT_DATE_STR = '' DB_NAME = 'trost_prod' TABLE_NAME = 'plants2' TABLE = [ 'id INT(11) AUTO_INCREMENT', 'aliquot INT(11)', 'name VARCHAR(45)', 'subspecies_...
'Location_Id': (3, 'location_id', int), 'Culture_Id': (4, 'culture_id', int), 'Sample_Id': (5, 'sampleid', int), 'Description': (6, 'description', str), 'created': (7, 'created', str)} ### def main(argv): if len(argv) == 0: sys.stderr.write('Missing input file.\nUsage: pytho...
columns_d = { 'Aliquot_Id': (0, 'aliquot', int), 'Name': (1, 'name', str), 'Subspecies_Id': (2, 'subspecies_id', int),
random_line_split
create_plants2table.py
#!/usr/bin/python import os import sys import math import glob import sql import process_xls as p_xls """ Change to whatever is needed. """ DEFAULT_DATE_STR = '' DB_NAME = 'trost_prod' TABLE_NAME = 'plants2' TABLE = [ 'id INT(11) AUTO_INCREMENT', 'aliquot INT(11)', 'name VARCHAR(45)', 'subspecies_...
(argv): if len(argv) == 0: sys.stderr.write('Missing input file.\nUsage: python create_plants2table.py <dir>\n') sys.exit(1) sql.write_sql_header(DB_NAME, TABLE_NAME, TABLE) dir_name = argv[0] fn = '%s/%s' % (dir_name, 'current_plants.xls') data, headers = p_xls.read_xls_d...
main
identifier_name
create_plants2table.py
#!/usr/bin/python import os import sys import math import glob import sql import process_xls as p_xls """ Change to whatever is needed. """ DEFAULT_DATE_STR = '' DB_NAME = 'trost_prod' TABLE_NAME = 'plants2' TABLE = [ 'id INT(11) AUTO_INCREMENT', 'aliquot INT(11)', 'name VARCHAR(45)', 'subspecies_...
""" Table writing logic is specific to this table, therefore it does not use sql.write_sql_table. """ for row in sql.prepare_sql_table(data, columns_d): # print row try: """ This adds the required values for subspecies.limsid and loc...
if len(argv) == 0: sys.stderr.write('Missing input file.\nUsage: python create_plants2table.py <dir>\n') sys.exit(1) sql.write_sql_header(DB_NAME, TABLE_NAME, TABLE) dir_name = argv[0] fn = '%s/%s' % (dir_name, 'current_plants.xls') data, headers = p_xls.read_xls_data(fn) """ ...
identifier_body
transport-negotiation-request.component.ts
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Component, Input, OnInit} from '@angular/core'; import { Location } from "@angular/common"; import { Router } from "@angular/ro...
// check whether the required fields for transport service details are filled or not isTransportServiceDetailsValid() { // no need to check transport service details for logistics services which are not transport services if (!this.isTransportService) { return true; } ...
{ this.location.back(); }
identifier_body
transport-negotiation-request.component.ts
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Component, Input, OnInit} from '@angular/core'; import { Location } from "@angular/common"; import { Router } from "@angular/...
(term: string): boolean { switch (term) { case "price": return (this.rfqPrice.itemPrice.value != null && this.rfqPrice.itemPrice.value != 0) || this.rfqPrice.itemPrice.currency != this.CURRENCIES[0]; case "payment-means": return this.PAYMENT_MEANS[0] != th...
isTermUpdated
identifier_name
transport-negotiation-request.component.ts
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Component, Input, OnInit} from '@angular/core'; import { Location } from "@angular/common"; import { Router } from "@angular/...
import { BPEService } from "../../bpe.service"; import { ThreadEventMetadata } from '../../../catalogue/model/publish/thread-event-metadata'; import { DiscountPriceWrapper } from "../../../common/discount-price-wrapper"; import { Text } from '../../../catalogue/model/publish/text'; import { TranslateService } from '@ng...
import { UserService } from "../../../user-mgmt/user.service"; import { CustomerParty } from "../../../catalogue/model/publish/customer-party"; import { SupplierParty } from "../../../catalogue/model/publish/supplier-party";
random_line_split
transport-negotiation-request.component.ts
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Component, Input, OnInit} from '@angular/core'; import { Location } from "@angular/common"; import { Router } from "@angular/ro...
return this.negotiationRequestForm.valid; } onSendRequest(): void { // send request for quotation this.callStatus.submit(); let rfq: RequestForQuotation = copy(this.bpDataService.requestForQuotation); let sellerId: string; let sellerFederationId: string; ...
{ return true; }
conditional_block
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.models import SocialApp, SocialToken import oauth2 as oauth import urllib, urllib2, json class TwitterAccount...
return False def request_url(self, url, args={}, callback=None): account = self.account app = SocialApp.objects.get_current(self.account.get_provider().id) tokens = SocialToken.objects.filter(app=app, account=account).order_by('-id') if tokens: ...
token = tokens[0] consumer = oauth.Consumer(key=app.key, secret=app.secret) access_token = oauth.Token(key=token.token, secret=token.token_secret) client = oauth.Client(consumer, access_token) try: response, data = client.request('https://api.twitter.com/1...
conditional_block
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.models import SocialApp, SocialToken import oauth2 as oauth import urllib, urllib2, json class TwitterAccount...
(self): account = self.account app = SocialApp.objects.get_current(self.account.get_provider().id) tokens = SocialToken.objects.filter(app=app, account=account).order_by('-id') if tokens: token = tokens[0] consumer = oauth.Consumer(key=app.key, secret=app...
has_valid_authentication
identifier_name
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.models import SocialApp, SocialToken import oauth2 as oauth import urllib, urllib2, json class TwitterAccount...
class TwitterProvider(OAuthProvider): id = 'twitter' name = 'Twitter' package = 'allauth.socialaccount.providers.twitter' account_class = TwitterAccount providers.registry.register(TwitterProvider)
screen_name = self.get_screen_name() return screen_name or super(TwitterAccount, self).__unicode__()
identifier_body
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.models import SocialApp, SocialToken import oauth2 as oauth import urllib, urllib2, json class TwitterAccount...
return False def request_url(self, url, args={}, callback=None): account = self.account app = SocialApp.objects.get_current(self.account.get_provider().id) tokens = SocialToken.objects.filter(app=app, account=account).order_by('-id') if tokens: ...
except urllib2.HTTPError: return False
random_line_split
Education.tsx
import React from 'react'; import { useTranslation } from 'react-i18next'; import School from "../components/School"; import SectionHeader from "../components/SectionHeader"; import FadeInAndGrowWhenVisible from "../components/animations/FadeInAndGrowWhenVisible"; import "./Education.css"; function Education() { c...
<School school={t("education.u_t_c.company")} schoolUrl="https://www.utc.fr/" location={t("education.u_t_c.location")} begin={new Date(2012,8,1)} end={new Date(2015,1,1)} diploma={t("education.u_t_c.job-title")} ...
<SectionHeader text={t("education.education")} /> <div className="education-container"> <FadeInAndGrowWhenVisible>
random_line_split
type_.rs
::mem; use std::ptr; use std::cell::RefCell; use libc::c_uint; #[derive(Clone, Copy, PartialEq, Debug)] #[repr(C)] pub struct Type { rf: TypeRef } macro_rules! ty { ($e:expr) => ( Type::from_ref(unsafe { $e })) } /// Wrapper for LLVM TypeRef impl Type { #[inline(always)] pub fn from_ref(r: TypeRef) ...
pub fn i32(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt32TypeInContext(ccx.llcx())) } pub fn i64(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt64TypeInContext(ccx.llcx())) } // Creates an integer type with the given number of bits, e.g. i24 pub fn ix(ccx: &CrateContext, nu...
}
random_line_split
type_.rs
::mem; use std::ptr; use std::cell::RefCell; use libc::c_uint; #[derive(Clone, Copy, PartialEq, Debug)] #[repr(C)] pub struct Type { rf: TypeRef } macro_rules! ty { ($e:expr) => ( Type::from_ref(unsafe { $e })) } /// Wrapper for LLVM TypeRef impl Type { #[inline(always)] pub fn from_ref(r: TypeRef) ...
// Creates an integer type with the given number of bits, e.g. i24 pub fn ix(ccx: &CrateContext, num_bits: u64) -> Type { ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), num_bits as c_uint)) } pub fn f32(ccx: &CrateContext) -> Type { ty!(llvm::LLVMFloatTypeInContext(ccx.llcx())) } ...
{ ty!(llvm::LLVMInt64TypeInContext(ccx.llcx())) }
identifier_body
type_.rs
::mem; use std::ptr; use std::cell::RefCell; use libc::c_uint; #[derive(Clone, Copy, PartialEq, Debug)] #[repr(C)] pub struct Type { rf: TypeRef } macro_rules! ty { ($e:expr) => ( Type::from_ref(unsafe { $e })) } /// Wrapper for LLVM TypeRef impl Type { #[inline(always)] pub fn from_ref(r: TypeRef) ...
(ccx: &CrateContext, els: &[Type], packed: bool) -> Type { let els : &[TypeRef] = unsafe { mem::transmute(els) }; ty!(llvm::LLVMStructTypeInContext(ccx.llcx(), els.as_ptr(), els.len() as c_uint, packed as Bool)) } ...
struct_
identifier_name
020_unpublish.ts
import { npmPublish, npmLogin, execSilent } from '../../utils/process'; import { createPackageJson } from '../../utils/utils'; import * as fs from '../../utils/fs'; export default function() { let authPath = 'morose/auth.json'; return Promise.resolve() .then(() => createPackageJson('package.json', 'test-packa...
return Promise.reject(''); }) .catch(() => Promise.reject('')); }
random_line_split
020_unpublish.ts
import { npmPublish, npmLogin, execSilent } from '../../utils/process'; import { createPackageJson } from '../../utils/utils'; import * as fs from '../../utils/fs'; export default function() { let authPath = 'morose/auth.json'; return Promise.resolve() .then(() => createPackageJson('package.json', 'test-packa...
return Promise.reject(''); }) .catch(() => Promise.reject('')); }
{ return Promise.resolve(); }
conditional_block
MultilineChartOutlined.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime")...
exports.default = _default;
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m22 6.92-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2...
random_line_split
test_ogrenci_iletisim_bilgileri.py
# -*- coding: utf-8 -*- from test_settings import Settings class TestCase(Settings):
# Posta Kodu'na deger yolluyor. self.driver.find_element_by_css_selector('#posta_kodu').send_keys('11000') # Telefon Numarasi'na deger yolluyor. self.driver.find_element_by_css_selector('#tel_no').send_keys('0534626286816') # Kaydet'e tikliyor self.driver.find_element_by_...
def test_sidebar(self): # Ayarlari yapiyor. self.do_settings() # Genel'e tikliyor. self.driver.find_element_by_css_selector( 'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-child(2)').click() # Ogrenci Iletisim Bilgilerine tikliyor. self.driver.find_el...
identifier_body
test_ogrenci_iletisim_bilgileri.py
# -*- coding: utf-8 -*- from test_settings import Settings class TestCase(Settings): def test_sidebar(self): # Ayarlari yapiyor. self.do_settings() # Genel'e tikliyor. self.driver.find_element_by_css_selector( 'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-chil...
'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-child(2)').click() # Ogrenci Iletisim Bilgilerine tikliyor. self.driver.find_element_by_css_selector('ul.in:nth-child(2) > li:nth-child(2) > a:nth-child(1)').click() # Ikamet Il'e deger gonderiyor. self.driver.find_eleme...
self.driver.find_element_by_css_selector('ul.in:nth-child(2) > li:nth-child(2) > a:nth-child(1)').click() self.do_login() # Genel'e tikliyor. self.driver.find_element_by_css_selector(
random_line_split
test_ogrenci_iletisim_bilgileri.py
# -*- coding: utf-8 -*- from test_settings import Settings class
(Settings): def test_sidebar(self): # Ayarlari yapiyor. self.do_settings() # Genel'e tikliyor. self.driver.find_element_by_css_selector( 'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-child(2)').click() # Ogrenci Iletisim Bilgilerine tikliyor. sel...
TestCase
identifier_name
ResultSet.js
/** * Simple wrapper class that represents a set of records returned by a Proxy. */ Ext.define('Ext.data.ResultSet', { /** * @property {Boolean} isResultSet * Identifies this class as a result set. */ isResultSet: true, $configPrefixed: false, config: { /** *...
} return count; } });
{ count = records.length; }
conditional_block
ResultSet.js
/** * Simple wrapper class that represents a set of records returned by a Proxy. */ Ext.define('Ext.data.ResultSet', { /** * @property {Boolean} isResultSet * Identifies this class as a result set. */ isResultSet: true, $configPrefixed: false, config: { /** *...
constructor: function(config) { this.initConfig(config); }, getCount: function() { var count = this.callParent(), records; if (!count) { records = this.getRecords(); if (records) { count = records.length; } } ...
* @param {Object} [config] Config object. */
random_line_split
cli.contribution.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
constructor( id: string, label: string, @IMessageService private messageService: IMessageService, @IEditorService private editorService: IEditorService ) { super(id, label); } private get target(): string { return `/usr/local/bin/${product.applicationName}`; } run(): TPromise<void> { return isAvai...
random_line_split
cli.contribution.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
class InstallAction extends Action { static ID = 'workbench.action.installCommandLine'; static LABEL = nls.localize('install', "Install '{0}' command in PATH", product.applicationName); constructor( id: string, label: string, @IMessageService private messageService: IMessageService, @IEditorService priva...
{ return pfs.exists(source); }
identifier_body
cli.contribution.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): string { return `/usr/local/bin/${product.applicationName}`; } run(): TPromise<void> { return isAvailable().then(isAvailable => { if (!isAvailable) { const message = nls.localize('not available', "This command is not available"); this.messageService.show(Severity.Info, message); return undefin...
target
identifier_name
cli.contribution.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return TPromise.wrapError(err); }); } }) .then<void>(() => this.messageService.show(Severity.Info, nls.localize('successIn', "Shell command '{0}' successfully installed in PATH.", product.applicationName))); }); } private isInstalled(): TPromise<boolean> { return pfs.lstat(this.target...
{ return this.createBinFolder() .then(() => createSymlink()); }
conditional_block
test_event.py
# -*- coding: utf-8 -*- """Test events classes. This file is part of PyVISA. :copyright: 2019-2020 by PyVISA Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import logging import pytest from pyvisa import constants, errors from pyvisa.events import Event from . import BaseT...
class SubEvent(Event): pass with pytest.raises(TypeError): Event.register(constants.EventType.exception)(SubEvent) assert Event._event_classes[constants.EventType.exception] is not SubEvent def test_event_context(self): event = Event(None, constants.EventT...
assert Event._event_classes[constants.EventType.clear] is SubEvent def test_register_event_cls_missing_attr(self):
random_line_split
test_event.py
# -*- coding: utf-8 -*- """Test events classes. This file is part of PyVISA. :copyright: 2019-2020 by PyVISA Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import logging import pytest from pyvisa import constants, errors from pyvisa.events import Event from . import BaseT...
event = Event(None, constants.EventType.clear, 1) assert event.context == 1 event.close() with pytest.raises(errors.InvalidSession): event.context
identifier_body
test_event.py
# -*- coding: utf-8 -*- """Test events classes. This file is part of PyVISA. :copyright: 2019-2020 by PyVISA Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import logging import pytest from pyvisa import constants, errors from pyvisa.events import Event from . import BaseT...
(Event): pass with pytest.raises(TypeError): Event.register(constants.EventType.exception)(SubEvent) assert Event._event_classes[constants.EventType.exception] is not SubEvent def test_event_context(self): event = Event(None, constants.EventType.clear, 1) ...
SubEvent
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.contrib.postgres.fields import ArrayField from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), migrations.swappable_...
('object_pk', models.TextField(verbose_name='object ID')), ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.C...
('content', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('path', ArrayField(size=None, base_field=models.IntegerField(), unique=True, editable=False, blank=True)),
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.contrib.postgres.fields import ArrayField from django.conf import settings class
(migrations.Migration): dependencies = [ ('sites', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', ...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.contrib.postgres.fields import ArrayField from django.conf import settings class Migration(migrations.Migration):
}, bases=(models.Model,), ), ]
dependencies = [ ('sites', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(verbose_name...
identifier_body
movie.js
$(function(){ $('.del').click(function(e){ var target = $(e.target); var id = target.data('id'); var tr = $('.item-id-'+id); $.ajax({ type:'DELETE', url:'/movie/del?id='+id }) .done(function(results){ if(results.success === 1)
}) }) $('#douban').blur(function(){ var douban = $(this); var id = douban.val(); if(id){ $.ajax({ url:'https://api.douban.com/v2/movie/subject/' + id, cache:true, type:'get', dataType:'jsonp', crossDomain:true, jsonp:'callback', success:function(data){ $('#inputTitle').va...
{ if (tr.length > 0) { tr.remove(); } }
conditional_block
movie.js
$(function(){ $('.del').click(function(e){ var target = $(e.target);
$.ajax({ type:'DELETE', url:'/movie/del?id='+id }) .done(function(results){ if(results.success === 1){ if (tr.length > 0) { tr.remove(); } } }) }) $('#douban').blur(function(){ var douban = $(this); var id = douban.val(); if(id){ $.ajax({ url:'https://api.douban.com/v2/m...
var id = target.data('id'); var tr = $('.item-id-'+id);
random_line_split
pack.py
""" This is used to pack testlib into a json Then you can load into database by using: manage.py loaddata <fixturename> fixturename here is `testlib.json` """ import hashlib import json from os import path, listdir def hash(binary): return hashlib.sha256(binary).hexdigest() category = ['checker', 'genera...
with open(path.join(father_dir, cat, file)) as fs: code = fs.read() with open(path.join(father_dir, cat, file), 'rb') as fs: code_binary = fs.read() data.append(dict(model='problem.SpecialProgram', fields=dict( fingerprint=hash(code_binary), ...
continue
conditional_block
pack.py
""" This is used to pack testlib into a json Then you can load into database by using: manage.py loaddata <fixturename> fixturename here is `testlib.json` """ import hashlib import json from os import path, listdir def hash(binary):
category = ['checker', 'generator', 'validator', 'validator'] father_dir = path.dirname(__file__) output_file = open(path.join(father_dir, 'testlib.json'), 'w') data = [] for cat in category: for file in listdir(path.join(father_dir, cat)): if file.startswith('.'): continue with open(path.join(father...
return hashlib.sha256(binary).hexdigest()
identifier_body
pack.py
""" This is used to pack testlib into a json Then you can load into database by using: manage.py loaddata <fixturename> fixturename here is `testlib.json` """ import hashlib import json from os import path, listdir def
(binary): return hashlib.sha256(binary).hexdigest() category = ['checker', 'generator', 'validator', 'validator'] father_dir = path.dirname(__file__) output_file = open(path.join(father_dir, 'testlib.json'), 'w') data = [] for cat in category: for file in listdir(path.join(father_dir, cat)): if file.startswit...
hash
identifier_name
pack.py
""" This is used to pack testlib into a json Then you can load into database by using: manage.py loaddata <fixturename> fixturename here is `testlib.json` """ import hashlib import json from os import path, listdir def hash(binary):
category = ['checker', 'generator', 'validator', 'validator'] father_dir = path.dirname(__file__) output_file = open(path.join(father_dir, 'testlib.json'), 'w') data = [] for cat in category: for file in listdir(path.join(father_dir, cat)): if file.startswith('.'): continue with open(path.join(father_di...
return hashlib.sha256(binary).hexdigest()
random_line_split
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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 ap...
// EXPORTS // export = iterator;
*/ declare function iterator( r: number, p: number, options?: Options ): RandIter;
random_line_split
test_io_csv.py
import pytest import os from polyglotdb import CorpusContext acoustic = pytest.mark.skipif( pytest.config.getoption("--skipacoustics"), reason="remove --skipacoustics option to run" ) def test_to_csv(acoustic_utt_config, export_test_dir): export_path = os.path.join(export_test_dir, 'results_export.csv')...
with CorpusContext(acoustic_utt_config) as g: q = g.query_graph(g.phone).filter(g.phone.label == 'aa') q = q.columns(g.phone.label, g.phone.duration, g.phone.begin) q = q.order_by(g.phone.begin) q.to_csv(export_path) # ignore ids ...
line = line.strip() if line == '': continue line = line.split(',') print(line) if i != 0: line = [line[0], float(line[1]), float(line[2])] assert line[0] == expected[i][0] assert line[1:] == pytest.approx(exp...
conditional_block
test_io_csv.py
import pytest import os from polyglotdb import CorpusContext acoustic = pytest.mark.skipif( pytest.config.getoption("--skipacoustics"), reason="remove --skipacoustics option to run" ) def test_to_csv(acoustic_utt_config, export_test_dir): export_path = os.path.join(export_test_dir, 'results_export.csv')...
if i != 0: line = [line[0], float(line[1]), float(line[2])] assert line[0] == expected[i][0] assert line[1:] == pytest.approx(expected[i][1:], 1e-3) else: assert line == expected[i] i += 1 with CorpusContext(acousti...
continue line = line.split(',') print(line)
random_line_split
test_io_csv.py
import pytest import os from polyglotdb import CorpusContext acoustic = pytest.mark.skipif( pytest.config.getoption("--skipacoustics"), reason="remove --skipacoustics option to run" ) def test_to_csv(acoustic_utt_config, export_test_dir):
line = line.split(',') print(line) if i != 0: line = [line[0], float(line[1]), float(line[2])] assert line[0] == expected[i][0] assert line[1:] == pytest.approx(expected[i][1:], 1e-3) else: assert line == exp...
export_path = os.path.join(export_test_dir, 'results_export.csv') with CorpusContext(acoustic_utt_config) as g: q = g.query_graph(g.phone).filter(g.phone.label == 'aa') q = q.columns(g.phone.label.column_name('label'), g.phone.duration.column_name('duration'), ...
identifier_body
test_io_csv.py
import pytest import os from polyglotdb import CorpusContext acoustic = pytest.mark.skipif( pytest.config.getoption("--skipacoustics"), reason="remove --skipacoustics option to run" ) def
(acoustic_utt_config, export_test_dir): export_path = os.path.join(export_test_dir, 'results_export.csv') with CorpusContext(acoustic_utt_config) as g: q = g.query_graph(g.phone).filter(g.phone.label == 'aa') q = q.columns(g.phone.label.column_name('label'), g.phone.duratio...
test_to_csv
identifier_name
project_tagkey_values.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.models import TagKey, TagKeyStatus, TagValue class ProjectTagKeyValuesEndp...
try: tagkey = TagKey.objects.get( project=project, key=lookup_key, status=TagKeyStatus.VISIBLE, ) except TagKey.DoesNotExist: raise ResourceDoesNotExist queryset = TagValue.objects.filter( project=...
lookup_key = key
conditional_block
project_tagkey_values.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.models import TagKey, TagKeyStatus, TagValue class
(ProjectEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project, key): """ List a tag's values Return a list of values associated with this key. {method} {path} """ if key in ('release', 'user', 'filename', 'function'): look...
ProjectTagKeyValuesEndpoint
identifier_name
project_tagkey_values.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.models import TagKey, TagKeyStatus, TagValue class ProjectTagKeyValuesEndp...
status=TagKeyStatus.VISIBLE, ) except TagKey.DoesNotExist: raise ResourceDoesNotExist queryset = TagValue.objects.filter( project=project, key=tagkey.key, ) return self.paginate( request=request, qu...
doc_section = DocSection.PROJECTS def get(self, request, project, key): """ List a tag's values Return a list of values associated with this key. {method} {path} """ if key in ('release', 'user', 'filename', 'function'): lookup_key = 'sentry:{0}'.f...
identifier_body
project_tagkey_values.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.models import TagKey, TagKeyStatus, TagValue class ProjectTagKeyValuesEndp...
lookup_key = key try: tagkey = TagKey.objects.get( project=project, key=lookup_key, status=TagKeyStatus.VISIBLE, ) except TagKey.DoesNotExist: raise ResourceDoesNotExist queryset = TagValue.objects....
random_line_split
dht_bencode.py
# -*- coding:utf-8 -*- def decode(data): try: value, idx = __decode(data, 0) retval = (True, value) except Exception as e: retval = (False, e.message) finally: return retval def encode(data): try: value = __encode(data) retval = (True, value) excep...
start_idx): values = [] while data[start_idx] != 'e': value, start_idx = __decode(data, start_idx) values.append(value) return values, start_idx + 1 # 解析字典 def __decode_dict(data, start_idx): dict_value = dict() while data[start_idx] != 'e': key, start_idx = __decode(data, ...
':', start_idx) str_len = int(data[start_idx: end_idx]) start_idx = end_idx + 1 end_idx = start_idx + str_len value = data[start_idx: end_idx] except Exception: raise Exception('__decode_str: error') return value, end_idx # 解析列表 def __decode_list(data,
identifier_body
dht_bencode.py
# -*- coding:utf-8 -*- def decode(data): try: value, idx = __decode(data, 0) retval = (True, value) except Exception as e: retval = (False, e.message) finally: return retval def encode(data): try: value = __encode(data) retval = (True, value) excep...
_list(data) else: raise Exception('__encode: Error') return value # 数字编码 def __encode_int(data): return 'i' + str(data) + 'e' # 字符串编码 def __encode_str(data): str_len = len(data) return str(str_len) + ':' + data # 列表编码 def __encode_list(data): ret = 'l' for datai in data: ...
): value = __encode
conditional_block
dht_bencode.py
# -*- coding:utf-8 -*- def decode(data): try: value, idx = __decode(data, 0) retval = (True, value) except Exception as e: retval = (False, e.message) finally: return retval def encode(data): try: value = __encode(data) retval = (True, value) excep...
return ret + 'e'
random_line_split
dht_bencode.py
# -*- coding:utf-8 -*- def decode(data): try: value, idx = __decode(data, 0) retval = (True, value) except Exception as e: retval = (False, e.message) finally: return retval def encode(data): try: value = __encode(data) retval = (True, value) excep...
nd_idx = data.index('e', start_idx) try: value = int(data[start_idx: end_idx]) except Exception: raise Exception('__decode_int: error') return value, end_idx + 1 # 解析字符串 def __decode_str(data, start_idx): try: end_idx = data.index(':', start_idx) str_len = int(data[star...
_idx): e
identifier_name
issue-8898.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let abc = [1, 2, 3]; let tf = [true, false]; let x = [(), ()]; let y = ~[(), ()]; let slice = x.slice(0,1); let z = @x; assert_repr_eq(abc, ~"[1, 2, 3]"); assert_repr_eq(tf, ~"[true, false]"); assert_repr_eq(x, ~"[(), ()]"); assert_repr_eq(y, ~"~[(), ()]"); assert_repr...
main
identifier_name
issue-8898.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let x = [(), ()]; let y = ~[(), ()]; let slice = x.slice(0,1); let z = @x; assert_repr_eq(abc, ~"[1, 2, 3]"); assert_repr_eq(tf, ~"[true, false]"); assert_repr_eq(x, ~"[(), ()]"); assert_repr_eq(y, ~"~[(), ()]"); assert_repr_eq(slice, ~"&[()]"); assert_repr_eq(&x, ~"&[(), ()]")...
let abc = [1, 2, 3]; let tf = [true, false];
random_line_split
issue-8898.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let abc = [1, 2, 3]; let tf = [true, false]; let x = [(), ()]; let y = ~[(), ()]; let slice = x.slice(0,1); let z = @x; assert_repr_eq(abc, ~"[1, 2, 3]"); assert_repr_eq(tf, ~"[true, false]"); assert_repr_eq(x, ~"[(), ()]"); assert_repr_eq(y, ~"~[(), ()]"); assert_repr_eq...
identifier_body
FeedEk.js
/* * FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API * http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk * Author : Engin KIZIL http://www.enginkizil.com */ (function ($) { $.fn.FeedEk = function (opt) { var def = $.extend({ FeedUrl: "http://jquery-plugi...
}; })(jQuery);
random_line_split
FeedEk.js
/* * FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API * http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk * Author : Engin KIZIL http://www.enginkizil.com */ (function ($) { $.fn.FeedEk = function (opt) { var def = $.extend({ FeedUrl: "http://jquery-plugi...
s += '</div>'; } }); $("#" + id).append('<ul class="feedEkList">' + s + '</ul>'); } }); }; })(jQuery);
{ s += itm.channel.item.description; }
conditional_block