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
vision.py
def complexity(full_matrix): global global_index global max_value """This function expects as an input a object of type FullMatrix which contains responses of all neurons in a sheet to stimuly with different varying parameter values. One of these parameters (features) has to be phase. In...
""" Recurrent helper function for complexity() """ global max_value global global_index if depth<size(fm.features): for i in range(size(fm.features[depth].values)): _complexity_rec(x,y,index + (i,),depth+1,fm) else: if max_value < f...
identifier_body
vso-build-models.ts
export interface RespositoryProperties { connectedServiceId: string; apiUrl: string; branchesUrl: string; cloneUrl: string; refsUrl: string; } export interface Repository { properties: RespositoryProperties; id: string; type: string; url: string; defaultBranch: string; clean...
VSTSRM_BuildWebAccessUrl?: string; AppUrl?: string; SlotUrl?: string; VSTSRM_AccountUrl?: string; VSTSRM_RepoUrl?: string; VSTSRM_AccountId?: string; }
targetSlot?: string; message?: string; VSTSRM_BuildDefinitionWebAccessUrl?: string; VSTSRM_ConfiguredCDEndPoint?: string;
random_line_split
teo.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
'Orara', 'Omuk', 'Okwamg’', 'Odung’el', 'Omaruk', 'Omodok’king’ol', 'Ojola', 'Opedel', 'Osokosokoma', 'Otibar', 'Olabor', 'Opoo' ] ], u, [['KK', 'BK'], u, ['Kabla ya Christo', 'Baada ya Christo']], 1, [0, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z...
['Rar', 'Muk', 'Kwa', 'Dun', 'Mar', 'Mod', 'Jol', 'Ped', 'Sok', 'Tib', 'Lab', 'Poo'], [
random_line_split
teo.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
(n: number): number { if (n === 1) return 1; return 5; } export default [ 'teo', [['Taparachu', 'Ebongi'], u, u], u, [ ['J', 'B', 'A', 'U', 'U', 'K', 'S'], ['Jum', 'Bar', 'Aar', 'Uni', 'Ung', 'Kan', 'Sab'], ['Nakaejuma', 'Nakaebarasa', 'Nakaare', 'Nakauni', 'Nakaung’on', 'Nakakany', 'Nakasabiti'], ...
plural
identifier_name
teo.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'teo', [['Taparachu', 'Ebongi'], u, u], u, [ ['J', 'B', 'A', 'U', 'U', 'K', 'S'], ['Jum', 'Bar', 'Aar', 'Uni', 'Ung', 'Kan', 'Sab'], ['Nakaejuma', 'Nakaebarasa', 'Nakaare', 'Nakauni', 'Nakaung’on', 'Nakakany', 'Nakasabiti'], ['Jum', 'Bar', 'Aar', 'Uni', 'Ung', 'Kan', 'Sab'] ], u, ...
{ if (n === 1) return 1; return 5; }
identifier_body
serializer.rs
has_sign, ref unit, } => { write_numeric(value, int_value, has_sign, dest)?; // Disambiguate with scientific notation. let unit = &**unit; // TODO(emilio): This doesn't handle e.g. 100E1m, which gets us ...
<'a, W> { inner: &'a mut W, } impl<'a, W> CssStringWriter<'a, W> where W: fmt::Write, { /// Wrap a text writer to create a `CssStringWriter`. pub fn new(inner: &'a mut W) -> CssStringWriter<'a, W> { CssStringWriter { inner: inner } } } impl<'a, W> fmt::Write for CssStringWriter<'a, W> wher...
CssStringWriter
identifier_name
serializer.rs
has_sign, ref unit, } => { write_numeric(value, int_value, has_sign, dest)?; // Disambiguate with scientific notation. let unit = &**unit; // TODO(emilio): This doesn't handle e.g. 100E1m, which gets us ...
impl<W: fmt::Write>
W: fmt::Write, { struct AssumeUtf8<W: fmt::Write>(W);
random_line_split
serializer.rs
} } Ok(()) } impl<'a> ToCss for Token<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { match *self { Token::Ident(ref value) => serialize_identifier(&**value, dest)?, Token::AtKeyword(ref value) => { dest....
{ // `value.value >= 0` is true for negative 0. if has_sign && value.is_sign_positive() { dest.write_str("+")?; } let notation = if value == 0.0 && value.is_sign_negative() { // Negative zero. Work around #20596. dest.write_str("-0")?; Notation { decimal_poin...
identifier_body
gulpfile.babel.js
'use strict'; import gulp from 'gulp'; import gutil from 'gulp-util'; import uglify from 'gulp-uglify'; import stylus from 'gulp-stylus'; import watch from 'gulp-watch'; import plumber from 'gulp-plumber'; import cleanCss from 'gulp-clean-css'; import imagemin from 'gulp-imagemin'; import concat from 'gulp-concat'; im...
gulp.task('default', ['minjs', 'stylus', 'images']);
random_line_split
managed.rs
api::JS::CurrentGlobalOrNull; use js::jsapi::JS::GCTraceKindToAscii; use js::jsapi::JS::HandleValue; use js::jsapi::JS::TraceKind; use js::jsapi::JS::Value; use js::jsapi::js::GetGlobalForObjectCrossCompartment; use js::jsapi::JSObject; use js::jsapi::JSTracer; use js::jsapi::JS_GetReservedSlot; use js::jsapi::JS_IsN...
} impl<'a, C, T> PartialEq for JSManaged<'a, C, T> { fn eq(&self, other: &Self) -> bool { self.raw == other.raw } } impl<'a, C, T> Eq for JSManaged<'a, C, T> { } unsafe impl<'a, C, T> JSTraceable for JSManaged<'a, C, T> where T: JSTraceable, { unsafe fn trace(&self, trc: *mut JSTracer) { ...
{ fmt.debug_struct("JSManaged") .field("js_object", &self.js_object) .field("raw", &self.raw) .finish() }
identifier_body
managed.rs
PhantomData, } } } impl<'a, C, T> Copy for JSManaged<'a, C, T> { } impl<'a, C, T> Debug for JSManaged<'a, C, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt.debug_struct("JSManaged") .field("js_object", &self.js_object) .field("raw", &self....
{ return Err(JSEvaluateErr::WrongClass); }
conditional_block
managed.rs
jsapi::JS::CurrentGlobalOrNull; use js::jsapi::JS::GCTraceKindToAscii; use js::jsapi::JS::HandleValue; use js::jsapi::JS::TraceKind; use js::jsapi::JS::Value; use js::jsapi::js::GetGlobalForObjectCrossCompartment; use js::jsapi::JSObject; use js::jsapi::JSTracer; use js::jsapi::JS_GetReservedSlot; use js::jsapi::JS_I...
/// Check to see if the current object is in the same compartment as another. pub fn in_compartment<S, D>(self, cx: &JSContext<S>) -> Option<JSManaged<'a, D, T::ChangeCompartment>> where T: JSCompartmental<C, D>, S: InCompartment<D>, { // The jsapi rust bindings don't expose cx.compa...
random_line_split
managed.rs
jsapi::JS::CurrentGlobalOrNull; use js::jsapi::JS::GCTraceKindToAscii; use js::jsapi::JS::HandleValue; use js::jsapi::JS::TraceKind; use js::jsapi::JS::Value; use js::jsapi::js::GetGlobalForObjectCrossCompartment; use js::jsapi::JSObject; use js::jsapi::JSTracer; use js::jsapi::JS_GetReservedSlot; use js::jsapi::JS_I...
<'b, S>(self, _: &'b JSContext<S>) -> T::Aged where S: CanAccess, C: Compartment, T: JSLifetime<'b>, T::Aged: Copy, 'a: 'b, { let result = unsafe { *(self.raw as *mut Option<T::Aged>) }; result.unwrap() } pub fn borrow<'b, S>(self, _: &'b JSContext<S>...
get
identifier_name
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
Err(msg) => println!("{}", msg) } } } fn convert_value(row: &Row, col_idx: i32) -> String { match row.get_checked::<i32, Value>(col_idx) { Ok(v) => { match v { Value::Null => "<null>".to_string(), Value::Integer(i) => i.to_string(), ...
); } println!(""); },
random_line_split
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
fn output_column(mut rows: Rows) -> () { while let Some(result_row) = rows.next() { match result_row { Ok(row) => println!("{}", convert_value(&row, 0)), Err(msg) => println!("{}", msg) } } } fn output_rows(mut rows: Rows) -> () { while let Some(result_row) = rows....
{ let mut stmt = conn.prepare(query).unwrap(); let rows = stmt.query(params).unwrap(); output(rows); }
identifier_body
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
Err(_) => "<type_fail>".to_string() } }
{ match v { Value::Null => "<null>".to_string(), Value::Integer(i) => i.to_string(), Value::Real(f) => f.to_string(), Value::Text(t) => t.to_string(), Value::Blob(_) => "<blob>".to_string() } }
conditional_block
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
(mut rows: Rows) -> () { while let Some(result_row) = rows.next() { match result_row { Ok(row) => { let cc = row.column_count(); for col_idx in 0..cc { print!("{}{}" , convert_value(&row, col_idx) ...
output_rows
identifier_name
deleteUsers.ts
import { Request, Response } from 'express'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; export const deleteUser = async (req: Request, res: Response) => { try { ...
return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto> { message: 'Failed to delete scout' , error: err }); } };
{ throw new Error('No scout to delete'); }
conditional_block
deleteUsers.ts
import { Request, Response } from 'express'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; export const deleteUser = async (req: Request, res: Response) => { try { ...
if (!deleted) { throw new Error('No scout to delete'); } return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto> { message: 'Failed to delete scout' , error: err }); } };
try { const user: User = await User.findByPk(req.params.userId); const deleted: Scout = await user.$remove('scouts', req.params.scoutId); await Scout.findByPk(req.params.scoutId).then((scout) => scout.destroy());
random_line_split
crossword2.py
''' >>> c = Crossword2() >>> c.embed((0, 0), HORIZONTAL, 'ANT') >>> c.embed((0, 0), VERTICAL, 'ATOM') >>> c.embed((1, 2), HORIZONTAL, 'IT') >>> c.embed((3, 0), HORIZONTAL, 'MEET') >>> c.dump() _#____ #ANT#_ _T#IT# _O____ #MEET# ...
(words, monitor=False): ''' >>> ans = list(build_crossword2(['ANT', 'ART', 'RAT'])) >>> ans[0].dump() #ANT# >>> ans[1].dump() _#___ #ANT# _R___ _T___ _#___ >>> ans[2].dump() ___#___ __#ANT# ___R___ #RAT#__ ___#___ >>> ans[3].dump() ___#_ ___R_ ...
build_crossword2
identifier_name
crossword2.py
>>> c.embed((0, 0), HORIZONTAL, 'ANT') >>> c.embed((0, 0), VERTICAL, 'ATOM') >>> c.embed((1, 2), HORIZONTAL, 'IT') >>> c.embed((3, 0), HORIZONTAL, 'MEET') >>> c.dump() _#____ #ANT#_ _T#IT# _O____ #MEET# _#____ >>> c.all_disc...
def __init__(self): self.grid = OpenGrid() self.connected = {} self.used_words = [] def copy(self): copied = Crossword2() copied.grid = self.grid.copy() copied.connected = self.connected.copy() copied.used_words = self.used_words[:] return copied ...
identifier_body
crossword2.py
''' >>> c = Crossword2() >>> c.embed((0, 0), HORIZONTAL, 'ANT') >>> c.embed((0, 0), VERTICAL, 'ATOM') >>> c.embed((1, 2), HORIZONTAL, 'IT') >>> c.embed((3, 0), HORIZONTAL, 'MEET') >>> c.dump() _#____ #ANT#_ _T#IT# _O____ #MEET# ...
return self.extract_sequences(line, poslist, direction, idx + 1, new_current_seq) else: new_current_seq = [(pos, direction, c)] return self.extract_sequences(line, poslist, direction, idx + 1, new_current_seq) def build_crossword2(words, monitor=False): ''' >>> ans...
new_current_seq.append((pos, direction, c))
conditional_block
crossword2.py
''' >>> c = Crossword2() >>> c.embed((0, 0), HORIZONTAL, 'ANT') >>> c.embed((0, 0), VERTICAL, 'ATOM') >>> c.embed((1, 2), HORIZONTAL, 'IT') >>> c.embed((3, 0), HORIZONTAL, 'MEET') >>> c.dump() _#____ #ANT#_ _T#IT# _O____ #MEET# ...
_#___ #ANT# _R___ _T___ _#___ >>> ans[2].dump() ___#___ __#ANT# ___R___ #RAT#__ ___#___ >>> ans[3].dump() ___#_ ___R_ _#_A_ #ANT# _R_#_ _T___ _#___ >>> ans[4].dump() _#___ _R___ #ANT# _T___ _#___ >>> ans[5].dump() ...
#ANT# >>> ans[1].dump()
random_line_split
xrootd.py
#!/usr/bin/env python # # XRootD # # XRootD package installer. # # Author M Mottram - 15/04/2016 <m.mottram@qmul.ac.uk> : First revision ####################################################################### import localpackage import os import stat import shutil class XRootD(localpackage.LocalPackage): """ Base ...
# Functions to override def get_dependencies(self): """ Return the dependency names as a list of names.""" return ["openssl-dev", "cmake-2.8.12"] def _is_downloaded(self): """ Check the tarball has been downloaded""" return self._system.file_exists(self.get_tar_name()) ...
random_line_split
xrootd.py
#!/usr/bin/env python # # XRootD # # XRootD package installer. # # Author M Mottram - 15/04/2016 <m.mottram@qmul.ac.uk> : First revision ####################################################################### import localpackage import os import stat import shutil class XRootD(localpackage.LocalPackage): """ Base ...
def _is_downloaded(self): """ Check the tarball has been downloaded""" return self._system.file_exists(self.get_tar_name()) def _is_installed(self): """ Check the script has been marked as executable.""" return self._system.file_exists("xrootd", os.path.join(self.get_install_p...
""" Return the dependency names as a list of names.""" return ["openssl-dev", "cmake-2.8.12"]
identifier_body
xrootd.py
#!/usr/bin/env python # # XRootD # # XRootD package installer. # # Author M Mottram - 15/04/2016 <m.mottram@qmul.ac.uk> : First revision ####################################################################### import localpackage import os import stat import shutil class XRootD(localpackage.LocalPackage): """ Base ...
(self): """ Download XRootD""" self._system.download_file("http://xrootd.org/download/v%s/%s" % (self._version, self.get_tar_name())) def _install(self): """ Mark the script as executable""" source_path = os.p...
_download
identifier_name
xrootd.py
#!/usr/bin/env python # # XRootD # # XRootD package installer. # # Author M Mottram - 15/04/2016 <m.mottram@qmul.ac.uk> : First revision ####################################################################### import localpackage import os import stat import shutil class XRootD(localpackage.LocalPackage): """ Base ...
cmake_opts = [source_path, "-DCMAKE_INSTALL_PREFIX=%s" % self.get_install_path(), "-DENABLE_PERL=FALSE"] cmake_command = "cmake" if self._dependency_paths["cmake-2.8.12"] is not None: cmake_command = "%s/bin/cmake" % self._dependency_paths...
os.makedirs(self.get_install_path())
conditional_block
dtoMapper.js
import defaultCardConfig from '../defaultCardConfig'; /** * Maps room to limited set of properties for export (room as file download). * * @param room * @return {undefined|{stories: *, exportedAt: number, roomId}} */ export function mapRoomExportDto(room) { if (!room) { return undefined; } return { ...
if (story.estimationsConfidence && story.estimationsConfidence[entry[0]]) { mappedEstm.confidence = story.estimationsConfidence[entry[0]]; } return mappedEstm; }) }; } /** * Maps to extensive set of properties. This is used to re-sync client state with backend state and should return...
{ const usernamesMap = users.reduce((total, currentUser) => { total[currentUser.id] = currentUser.username || currentUser.id; return total; }, {}); return { title: story.title, description: story.description, consensus: story.consensus, estimations: Object.entries(story.estimations).map((...
identifier_body
dtoMapper.js
import defaultCardConfig from '../defaultCardConfig'; /** * Maps room to limited set of properties for export (room as file download). * * @param room * @return {undefined|{stories: *, exportedAt: number, roomId}} */ export function mapRoomExportDto(room) { if (!room) { return undefined; } return { ...
(room) { if (!room) { return undefined; } const { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, cardConfig } = room; return { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, ...
mapRoomStateDto
identifier_name
dtoMapper.js
import defaultCardConfig from '../defaultCardConfig'; /** * Maps room to limited set of properties for export (room as file download). * * @param room * @return {undefined|{stories: *, exportedAt: number, roomId}} */ export function mapRoomExportDto(room) { if (!room) { return undefined; } return { ...
const { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, cardConfig } = room; return { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, passwordProtected: !!room.password, cardConf...
{ return undefined; }
conditional_block
dtoMapper.js
import defaultCardConfig from '../defaultCardConfig'; /** * Maps room to limited set of properties for export (room as file download). * * @param room * @return {undefined|{stories: *, exportedAt: number, roomId}} */ export function mapRoomExportDto(room) { if (!room) { return undefined; } return { ...
return { title: story.title, description: story.description, consensus: story.consensus, estimations: Object.entries(story.estimations).map((entry) => { const matchingUser = usernamesMap[entry[0]]; const mappedEstm = { username: matchingUser ? matchingUser : entry[0], valu...
function mapStoryExportDto(story, users) { const usernamesMap = users.reduce((total, currentUser) => { total[currentUser.id] = currentUser.username || currentUser.id; return total; }, {});
random_line_split
sns.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
""" This hook is deprecated. Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`. """ def __init__(self, *args, **kwargs): warnings.warn( "This hook is deprecated. " "Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`.", DeprecationWarn...
return self.get_conn().publish(**publish_kwargs) class AwsSnsHook(SnsHook):
random_line_split
sns.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
( self, target_arn: str, message: str, subject: Optional[str] = None, message_attributes: Optional[dict] = None, ): """ Publish a message to a topic or an endpoint. :param target_arn: either a TopicArn or an EndpointArn :param message: the def...
publish_to_target
identifier_name
sns.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
warnings.warn( "This hook is deprecated. " "Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`.", DeprecationWarning, stacklevel=2, ) super().__init__(*args, **kwargs)
identifier_body
sns.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
raise TypeError( f'Values in MessageAttributes must be one of bytes, str, int, float, or iterable; got {type(o)}' ) class SnsHook(AwsBaseHook): """ Interact with Amazon Simple Notification Service. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to...
return {'DataType': 'String.Array', 'StringValue': json.dumps(o)}
conditional_block
container.ts
= registry as Registry & DebugRegistry; this.owner = options.owner || null; this.cache = dictionary(options.cache || null); this.factoryManagerCache = dictionary(options.factoryManagerCache || null); this.isDestroyed = false; this.isDestroying = false; if (DEBUG) { this.validationCache =...
(container: Container, fullName: string, options: LookupOptions = {}) { assert( 'EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to lookup', EMBER_MODULE_UNIFICATION || !options.namespace ); let normalizedName = fullName; if (options.source || options.namespace) { normalizedNam...
lookup
identifier_name
container.ts
}, }; })(); } } catch (e) { // ignore } } export interface ContainerOptions { owner?: Owner; cache?: { [key: string]: CacheMember }; factoryManagerCache?: { [key: string]: FactoryManager<any, any> }; validationCache?: { [key: string]: boolean }; } /** A container used to ...
{ containers.delete(values[i]); }
conditional_block
container.ts
.registry = registry as Registry & DebugRegistry; this.owner = options.owner || null; this.cache = dictionary(options.cache || null); this.factoryManagerCache = dictionary(options.factoryManagerCache || null); this.isDestroyed = false; this.isDestroying = false; if (DEBUG) { this.validati...
```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> fal...
random_line_split
container.ts
= registry as Registry & DebugRegistry; this.owner = options.owner || null; this.cache = dictionary(options.cache || null); this.factoryManagerCache = dictionary(options.factoryManagerCache || null); this.isDestroyed = false; this.isDestroying = false; if (DEBUG) { this.validationCache =...
function instantiateFactory( container: Container, normalizedName: string, fullName: string, options: FactoryOptions ) { let factoryManager = factoryFor(container, normalizedName, fullName); if (factoryManager === undefined) { return; } // SomeClass { singleton: true, instantiate: true } | { sin...
{ return ( instantiate !== false && (singleton !== false || isSingleton(container, fullName)) && isInstantiatable(container, fullName) ); }
identifier_body
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
let mut proto = RootedObject::new(cx, ptr::null_mut()); if GetObjectProto(cx, proxy, proto.handle_mut()) == 0 { desc.get().obj = ptr::null_mut(); return JSTrue; } JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc) } /// Defines an expando on the given `proxy`. pub unsafe exte...
{ return JSTrue; }
conditional_block
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> u8 { let handler = GetProxyHandler...
get_property_descriptor
identifier_name
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
if expando.is_null() { expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null()); assert!(!expando.is_null()); SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, ObjectValue(&*expando)); } expando } } /// Set the property descriptor's ob...
let mut expando = get_expando_object(obj);
random_line_split
proxyhandler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
/// Deletes an expando off the given `proxy`. pub unsafe extern fn delete(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut ObjectOpResult) -> u8 { let expando = RootedObject::new(cx, get_expando_object(proxy)); if expando.ptr.is_null() { (*bp).code_ = 0 /* Ok...
{ //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385 let setter: *const libc::c_void = mem::transmute(desc.get().setter); let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub); if (desc.get().attrs & JSPROP_GETTER) != 0 && setter == setter_stub { (*result...
identifier_body
component.ts
/** @module ember */ /** The `{{component}}` helper lets you add instances of `Component` to a template. See [Component](/ember/release/classes/Component) for additional information on how a `Component` functions. `{{component}}`'s primary use is for cases where you want to dynamically change which type of...
Which outputs an input whose value is already bound to `model.name` and `placeholder` is "Username". When yielding the component without the hash helper use the `component` helper. For example, below is a `full-name` component template: ```handlebars {{yield (component "my-input-component" value=model.na...
{{form.nameInput placeholder="Username"}} {{/person-form}} ```
random_line_split
Buttons.ts
import Editor from 'tinymce/core/api/Editor'; import { NodeChangeEvent } from 'tinymce/core/api/EventTypes'; import { Menu, Toolbar } from 'tinymce/core/api/ui/Ui'; import { EditorEvent } from 'tinymce/core/api/util/EventDispatcher'; import Tools from 'tinymce/core/api/util/Tools'; import * as Options from '../api/Opt...
else { addButton(editor, id, tooltip, cmd, nodeName, styles); } }; const register = (editor: Editor): void => { addControl(editor, 'numlist', 'Numbered list', 'InsertOrderedList', ListType.OrderedList, Options.getNumberStyles(editor)); addControl(editor, 'bullist', 'Bullet list', 'InsertUnorderedList', List...
{ addSplitButton(editor, id, tooltip, cmd, nodeName, styles); }
conditional_block
Buttons.ts
import Editor from 'tinymce/core/api/Editor'; import { NodeChangeEvent } from 'tinymce/core/api/EventTypes'; import { Menu, Toolbar } from 'tinymce/core/api/ui/Ui'; import { EditorEvent } from 'tinymce/core/api/util/EventDispatcher'; import Tools from 'tinymce/core/api/util/Tools'; import * as Options from '../api/Opt...
fetch: (callback) => { const items = Tools.map(styles, (styleValue): Menu.ChoiceMenuItemSpec => { const iconStyle = nodeName === ListType.OrderedList ? 'num' : 'bull'; const iconName = styleValue === 'disc' || styleValue === 'decimal' ? 'default' : styleValue; const itemValue = styleVa...
random_line_split
Dados.py
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","|...
(*repeticiones): tiradas = 1 if (len(repeticiones) > 0): tiradas = repeticiones[0] else: tiradas = 1 for i in range(0,tiradas): numero = a.generar() resultado = diccio[numero] for fila in resultado: print fila s...
dado
identifier_name
Dados.py
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","|...
if(ingreso == 0): print "KeepRollingDice4Life" seguir = False else: dado(ingreso) # print "otro?" # seguir = validador.ingresarSINO()
print "indique la cantidad de tiradas:" ingreso = validador.ingresar(int,validador.entre,0,20)
random_line_split
Dados.py
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","|...
else: dado(ingreso) # print "otro?" # seguir = validador.ingresarSINO()
print "KeepRollingDice4Life" seguir = False
conditional_block
Dados.py
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","|...
seguir = True while (seguir): print "indique la cantidad de tiradas:" ingreso = validador.ingresar(int,validador.entre,0,20) if(ingreso == 0): print "KeepRollingDice4Life" seguir = False else: dado(ingreso) # print "otro?" # seguir = ...
tiradas = 1 if (len(repeticiones) > 0): tiradas = repeticiones[0] else: tiradas = 1 for i in range(0,tiradas): numero = a.generar() resultado = diccio[numero] for fila in resultado: print fila
identifier_body
myocontrol.js
var net = require('net'); var HOST = '128.197.50.236'; var PORT = 55000; var n=1; var client = new net.Socket(); var RollingSpider = new require('rolling-spider'); var quad = new RollingSpider({ logger: console.log }); var flying = false; var inFlip = false; var land = false; var count=0; var prevControls; qu...
() { inFlip = false; } // Add a 'clos joystick.on('data', function(buf) { /* var controls = parseControls(buf); if (!prevControls) prevControls = controls; if (prevControls.buttons[0] === 0 && controls.buttons[0] === 1) { if (flying) { ...
flipDone
identifier_name
myocontrol.js
var net = require('net'); var HOST = '128.197.50.236'; var PORT = 55000; var n=1; var client = new net.Socket(); var RollingSpider = new require('rolling-spider'); var quad = new RollingSpider({ logger: console.log }); var flying = false; var inFlip = false; var land = false; var count=0; var prevControls; quad...
//var hid = require('node-hid'); // console.log(hid.devices()); // Logitech Extreme 3D Pro's vendorID and productID: 1133:49685 (i.e. 046d:c215) //var joystick = new hid.HID(1133, 49685); // console.log(joystick);
}); */
random_line_split
myocontrol.js
var net = require('net'); var HOST = '128.197.50.236'; var PORT = 55000; var n=1; var client = new net.Socket(); var RollingSpider = new require('rolling-spider'); var quad = new RollingSpider({ logger: console.log }); var flying = false; var inFlip = false; var land = false; var count=0; var prevControls; qu...
// Add a 'clos joystick.on('data', function(buf) { /* var controls = parseControls(buf); if (!prevControls) prevControls = controls; if (prevControls.buttons[0] === 0 && controls.buttons[0] === 1) { if (flying) { quad.land();...
{ inFlip = false; }
identifier_body
image_filters.py
# http://lodev.org/cgtutor/filtering.html import cv2 import numpy as np #img = cv2.imread('../images/input_sharp_edges.jpg', cv2.IMREAD_GRAYSCALE) img = cv2.imread('../images/input_tree.jpg') rows, cols = img.shape[:2] #cv2.imshow('Original', img) ################### # Motion Blur size = 15 kernel_motion_blur = np.z...
[0,0,-1]]) gray_img = cv2.cvtColor(img_emboss_input,cv2.COLOR_BGR2GRAY) output_1 = cv2.filter2D(gray_img, -1, kernel_emboss_1) output_2 = cv2.filter2D(gray_img, -1, kernel_emboss_2) output_3 = cv2.filter2D(gray_img, -1, kernel_emboss_3) cv2.imshow('Input', img_emboss_input) cv2.imshow('Embo...
[0,0,0],
random_line_split
test_info_all.py
# -*- coding: utf-8 -*- import pytest import sys from aerospike import exception as e from .test_base_class import TestBaseClass aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike python client.") sys.exit(1) @pytest.mark.usefixtures("as_connectio...
assert isinstance(nodes_info, dict) assert nodes_info.values() is not None def test_info_all_with_none_request(self): ''' Test that sending None as the request raises an error ''' request = None with pytest.raises(e.ParamError): self.as_connecti...
request = "fake_request_string_not_real" hosts = [host for host in self.connection_config['hosts']] nodes_info = self.as_connection.info_all(request)
random_line_split
test_info_all.py
# -*- coding: utf-8 -*- import pytest import sys from aerospike import exception as e from .test_base_class import TestBaseClass aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike python client.") sys.exit(1) @pytest.mark.usefixtures("as_connectio...
assert found def test_info_all_with_config_for_statistics_and_policy(self): request = "statistics" policy = {'timeout': 1000} hosts = [host for host in self.connection_config['hosts']] nodes_info = self.as_connection.info_all( request, policy) assert...
if value is not None: if container_name in value: found = True
conditional_block
test_info_all.py
# -*- coding: utf-8 -*- import pytest import sys from aerospike import exception as e from .test_base_class import TestBaseClass aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike python client.") sys.exit(1) @pytest.mark.usefixtures("as_connectio...
(self): request = "statistics" nodes_info = self.as_connection.info_all(request, None) assert nodes_info is not None assert type(nodes_info) == dict @pytest.mark.parametrize( "container_type, container_name", [ ('namespaces', 'test'), ('sets...
test_info_all_with_None_policy
identifier_name
test_info_all.py
# -*- coding: utf-8 -*- import pytest import sys from aerospike import exception as e from .test_base_class import TestBaseClass aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike python client.") sys.exit(1) @pytest.mark.usefixtures("as_connectio...
def test_info_all_without_connection(self): """ Test info positive for sets without connection """ client1 = aerospike.client(self.connection_config) with pytest.raises(e.ClusterError) as err_info: client1.info_all('sets') def test_info_all_with_invalid_po...
with pytest.raises(TypeError) as err_info: self.as_connection.info_all()
identifier_body
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
/// Seek pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let end = self.window.content.size; self.seek = match pos { SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize, SeekFrom::Current(offset) => cmp::min(end as i64, cmp::max(0, self...
{ let content = &mut self.window.content; let size = cmp::min(content.size - self.seek, buf.len()); unsafe { Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size); } self.seek += size; Ok(size) }
identifier_body
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
(&self) -> Result<Box<Resource>> { Ok(box Resource { window: Window::new(self.window.point, self.window.size, self.window.title.clone()), seek: self.seek, }) } /// Return the url of this resource pub fn ...
dup
identifier_name
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
/// Write to resource pub fn write(&mut self, buf: &[u8]) -> Result<usize> { let content = &mut self.window.content; let size = cmp::min(content.size - self.seek, buf.len()); unsafe { Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size); } ...
random_line_split
Crawler.py
"Generic Crawler object to read from a url" # coding: utf8 import re from BeautifulSoup import BeautifulSoup import urllib2 MAXTRIES = 4 def removewhitespaces(string): "Removes whitespaces, newlines and carriage returns from string" return re.sub('\s', '', string) def removewhitespacesstartandend(string): ...
def find(self, string): "Placeholder" string = string.decode('utf-8') + self.htmlpage return string
try: htmltext = urllib2.urlopen(url) self.htmlpage = BeautifulSoup(htmltext) self.url = url return except urllib2.URLError: tries += 1
conditional_block
Crawler.py
"Generic Crawler object to read from a url" # coding: utf8 import re from BeautifulSoup import BeautifulSoup import urllib2 MAXTRIES = 4 def removewhitespaces(string): "Removes whitespaces, newlines and carriage returns from string" return re.sub('\s', '', string) def removewhitespacesstartandend(string): ...
(self, string): "Placeholder" string = string.decode('utf-8') + self.htmlpage return string
find
identifier_name
Crawler.py
"Generic Crawler object to read from a url" # coding: utf8 import re from BeautifulSoup import BeautifulSoup import urllib2 MAXTRIES = 4 def removewhitespaces(string): "Removes whitespaces, newlines and carriage returns from string"
"""Removes whitespaces, newlines and carriage from the start and end of a string""" string = re.sub('^\s', '', string) return re.sub('\s$', '', string) def appendparameters(string, parameters): """Returns a string with each key and value from the dict parameters with the formatting: string?key...
return re.sub('\s', '', string) def removewhitespacesstartandend(string):
random_line_split
Crawler.py
"Generic Crawler object to read from a url" # coding: utf8 import re from BeautifulSoup import BeautifulSoup import urllib2 MAXTRIES = 4 def removewhitespaces(string): "Removes whitespaces, newlines and carriage returns from string" return re.sub('\s', '', string) def removewhitespacesstartandend(string): ...
def loadpage(self, url): "Loads html page from url at self.htmlfile and its text at htmltext" tries = 0 while tries < MAXTRIES: try: htmltext = urllib2.urlopen(url) self.htmlpage = BeautifulSoup(htmltext) self.url = url ...
self.url = None self.htmlpage = None
identifier_body
conditional-canonicals.js
var Builder = require('../index'); var builder = new Builder('test/fixtures/conditional-tree'); builder.loadConfigSync('test/fixtures/conditional-tree.config.js'); var baseURL = builder.loader.baseURL; builder.config({ defaultJSExtensions: true });
test('Interpolation', function() { assert.equal(builder.getCanonicalName(baseURL + 'interpolated-#{' + baseURL + 'conditions.js|test}.js'), 'interpolated-#{conditions.js|test}.js'); }); test('Plugin interpolation', function() { assert.equal(builder.getCanonicalName(baseURL + 'pkg/test-#{' + baseURL + 'con...
suite('Conditional Canonical Names', function() { test('Package environment canonical', function() { assert.equal(builder.getCanonicalName(baseURL + 'pkg#:env-condition'), 'pkg#:env-condition'); });
random_line_split
xssencode.py
import random def randomurl(): chars='abcdefghijklmnopqrstuvwxyz' length=random.randint(5, 20) choice=random.choice return ''.join(choice(chars) for i in range(length))+'.com' def xssencode(javascript):
if __name__=='__main__': attack="alert('XSS: '+document.cookie)" print('\n'.join(xssencode(attack)))
javascript2='eval(String.fromCharCode(%s))' % ','.join(str(ord(i)) for i in javascript) for js in [javascript, javascript2]: options=['<script>{}</script>', '<a onmouseover="{}">%s</a>' % (' '*random.randint(0, 250)), '<dev onmouseover="{}">%s</dev>' % (' '*random.randint(0, 250)), ...
identifier_body
xssencode.py
import random def randomurl(): chars='abcdefghijklmnopqrstuvwxyz' length=random.randint(5, 20) choice=random.choice return ''.join(choice(chars) for i in range(length))+'.com' def xssencode(javascript): javascript2='eval(String.fromCharCode(%s))' % ','.join(str(ord(i)) for i in javascript) ...
i=''.join(a.upper() if random.randint(0,1) else a.lower() for a in i) i=''.join(a if random.randint(0,1) or a!='>' else ' >' for a in i) i=''.join(a if random.randint(0,1) or a!=' ' else ' ' for a in i) yield i.format(js) if __name__=='__main__': attack="alert('XSS: ...
'<body onload={}>',] for i in options:
random_line_split
xssencode.py
import random def randomurl(): chars='abcdefghijklmnopqrstuvwxyz' length=random.randint(5, 20) choice=random.choice return ''.join(choice(chars) for i in range(length))+'.com' def xssencode(javascript): javascript2='eval(String.fromCharCode(%s))' % ','.join(str(ord(i)) for i in javascript) ...
attack="alert('XSS: '+document.cookie)" print('\n'.join(xssencode(attack)))
conditional_block
xssencode.py
import random def randomurl(): chars='abcdefghijklmnopqrstuvwxyz' length=random.randint(5, 20) choice=random.choice return ''.join(choice(chars) for i in range(length))+'.com' def
(javascript): javascript2='eval(String.fromCharCode(%s))' % ','.join(str(ord(i)) for i in javascript) for js in [javascript, javascript2]: options=['<script>{}</script>', '<a onmouseover="{}">%s</a>' % (' '*random.randint(0, 250)), '<dev onmouseover="{}">%s</dev>' % (' '*random.randint...
xssencode
identifier_name
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
(cell: u8, digit: u8) -> Candidate { assert!(cell < 81); assert!(0 < digit && digit < 10); Candidate { cell: Cell::new(cell), digit: Digit::new(digit), } } /// Returns the row of this candidate's cell #[inline] pub fn row(self) -> Row { s...
new
identifier_name
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
#[inline] pub fn col(self) -> Col { self.cell.col() } /// Returns the field (box) of this candidate's cell #[inline] pub fn block(self) -> Block { self.cell.block() } #[inline] pub(crate) fn digit_set(self) -> Set<Digit> { self.digit.as_set() } }
/// Returns the columns of this candidate's cell
random_line_split
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
/// Returns the columns of this candidate's cell #[inline] pub fn col(self) -> Col { self.cell.col() } /// Returns the field (box) of this candidate's cell #[inline] pub fn block(self) -> Block { self.cell.block() } #[inline] pub(crate) fn digit_set(self) -> S...
{ self.cell.row() }
identifier_body
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
fn parse_process(process_line: &str) -> Option<String> { parse(r#"users:\(\("([\w\-\+]+)""#, process_line) } fn parse_pid(process_line: &str) -> Option<String> { parse(r"pid=(\d+)", process_line) } fn parse_ip_addresses(process_line: &str) -> Option<(String, String)> { let regex = Regex::new(r"(\d{1,3}.\d...
}
random_line_split
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
let from = from_capture .unwrap() .get(1) .map_or("".into(), |s| s.as_str().into()); let to = to_capture .unwrap() .get(1) .map_or("".into(), |s| s.as_str().into()); Some((from, to)) } #[derive(Debug)] pub str...
{ return None }
conditional_block
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
(process_line: &str) -> Option<Process> { let (from, to) = match parse_ip_addresses(process_line) { Some((f, t)) => { let from = IpAddr::from_str(&f); let to = IpAddr::from_str(&t); if from.is_ok() && to.is_ok() { (from.unwrap(), to...
new
identifier_name
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
fn parse_ip_addresses(process_line: &str) -> Option<(String, String)> { let regex = Regex::new(r"(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})+:\d+").unwrap(); let mut captures = regex.captures_iter(&process_line); let from_capture = captures.next(); let to_capture = captures.next(); if from_capture.is_none()...
{ parse(r"pid=(\d+)", process_line) }
identifier_body
customize26_27.py
# Copyright (c) 2019 2021 by Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
self.default(node) self.n_call = n_call
args_node = node[-2] if args_node == 'expr': n = args_node[0] if n == 'generator_exp': node.kind = 'call_generator' pass pass
conditional_block
customize26_27.py
# Copyright (c) 2019 2021 by Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
# A function with one argument. If this is a generator, # no parenthesis is needed. args_node = node[-2] if args_node == 'expr': n = args_node[0] if n == 'generator_exp': node.kind = 'call_generator' ...
if version > (2, 6): TABLE_DIRECT.update({ 'except_cond2': ( '%|except %c as %c:\n', 1, 5 ), # When a generator is a single parameter of a function, # it doesn't need the surrounding parenethesis. 'call_generator': ('%c%P', 0, (1, -1, ', ', 100)), }) e...
identifier_body
customize26_27.py
# Copyright (c) 2019 2021 by Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
(self, version): ######################################## # Python 2.6+ # except <condition> as <var> # vs. older: # except <condition> , <var> # # For 2.6 we use the older syntax which # matches how we parse this in bytecode ######################################## if ver...
customize_for_version26_27
identifier_name
customize26_27.py
# Copyright (c) 2019 2021 by Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
# except <condition> , <var> # # For 2.6 we use the older syntax which # matches how we parse this in bytecode ######################################## if version > (2, 6): TABLE_DIRECT.update({ 'except_cond2': ( '%|except %c as %c:\n', 1, 5 ), # When a generat...
# Python 2.6+ # except <condition> as <var> # vs. older:
random_line_split
pxss.py
Pointer private13; ('private14', c_char_p), # XPointer private14; ('max_request_size', c_uint), # unsigned max_request_size; /* maximum number 32 bit words in request*/ ('db', c_void_p), # struct _XrmHashBucketRec *db; ('private15', c_int), # int (*private15)( ...
wait_time = self.info.til_or_since
conditional_block
pxss.py
('mheight', c_int), ('ndepths', c_int), # int ndepths; /* number of depths possible */ ('depths', c_void_p), # Depth *depths; /* list of allowable depths on the screen */ ('root_depth', c_int), # int root_depth; /* bits per pixel */ ('root_vis...
_p_display = libXss.XOpenDisplay('') display = _p_display.contents # Get DefaultRootWindow(display), which is a macro # Xlib.h # #define DefaultRootWindow(dpy) (ScreenOfDisplay(dpy,DefaultScreen(dpy))->root) # #define ScreenOfDisplay(dpy, scr)(&((_XPrivDisplay)dpy)->screens[scr]) # #define DefaultScreen(dpy) (((_XP...
# Specify return types libXss.XOpenDisplay.restype = POINTER(Display) libXss.XScreenSaverAllocInfo.restype = POINTER(XScreenSaverInfo)
random_line_split
pxss.py
('mheight', c_int), ('ndepths', c_int), # int ndepths; /* number of depths possible */ ('depths', c_void_p), # Depth *depths; /* list of allowable depths on the screen */ ('root_depth', c_int), # int root_depth; /* bits per pixel */ ('root_vis...
(self): """Returns a tuple: (state_change, suggested_time_till_next_check, idle_time) suggested_time_till_next_check and idle_time is in milliseconds. state_change is one of:
check_idle
identifier_name
pxss.py
*/ ('mheight', c_int), ('ndepths', c_int), # int ndepths; /* number of depths possible */ ('depths', c_void_p), # Depth *depths; /* list of allowable depths on the screen */ ('root_depth', c_int), # int root_depth; /* bits per pixel */ ('root...
# Specify return types libXss.XOpenDisplay.restype = POINTER(Display) libXss.XScreenSaverAllocInfo.restype = POINTER(XScreenSaverInfo) _p_display = libXss.XOpenDisplay('') display = _p_display.contents # Get DefaultRootWindow(display), which is a macro # Xlib.h # #define DefaultRootWindow(dpy) (ScreenOfDisplay(d...
if p_display is None: p_display = _p_display if default_root_window is None: default_root_window = _default_root_window if p_info is None: p_info = _p_info libXss.XScreenSaverQueryInfo(p_display, default_root_window, p_info) return p_info.contents
identifier_body
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
(&mut self, r: usize, c: usize) -> bool { self.cells[c + r * self.sz].hit = true; self.is_ship(r, c) } fn count_ships(&self) -> usize { let mut h = 0; for i in 0..self.sz * self.sz { if self.cells[i].ship { h += 1; } } h ...
check_shot
identifier_name
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
else { print!("~\t"); } } println!(""); } println!("Ships: {}, Hits: {}.", self.count_ships(), self.count_hits()); } }
{ print!("*\t"); }
conditional_block
board.rs
pub struct Board { sz: usize,
struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hit: false, ship: false, }); ...
cells: Vec<Cell> }
random_line_split
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
pub fn place_horizontal_ship(&mut self, x_start: usize, y: usize, len: &usize) { for x in x_start..(x_start + len) { self.cells[y * self.sz + x] = Cell { ship: true, hit: false}; } } pub fn place_vertical_ship(&mut self, x: usize, y_start: usize, len: &usize) { for y i...
{ let mut h = 0; for i in 0..self.sz * self.sz { if self.cells[i].ship { h += 1; } } h }
identifier_body
grade_java.py
import config, json, cgi, sys, Websheet, re, os def grade(reference_solution, student_solution, translate_line, websheet, student): if not re.match(r"^\w+$", websheet.classname): return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>") dump = { ...
compileRun = config.run_java(["traceprinter/ramtools/CompileToBytes"], json.dumps(dump)) compileResult = compileRun.stdout if (compileResult==""): return ("Internal Error (Compiling)", "<pre>\n" + cgi.escape(compileRun.stderr) + "</pre>"+"<!--"+compileRun._toString()+"-...
depws = Websheet.Websheet.from_name(dep) if depws == None: return ("Internal Error", "Dependent websheet " + dep + " does not exist"); submission = config.load_submission(student, dep, True) if submission == False: return("Dependency Error", "<div class='dependency-err...
conditional_block
grade_java.py
import config, json, cgi, sys, Websheet, re, os def grade(reference_solution, student_solution, translate_line, websheet, student): if not re.match(r"^\w+$", websheet.classname): return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>") dump = { ...
(s, t, u): # substring from of s from after t to before u if t not in s: raise ValueError("Can't ssf("+s+","+t+","+u+")") s = s[s.index(t)+len(t) : ] return s[ : s.index(u)] if "<div class='error'>Runtime error:" in runtimeOutput: category = "Runtime Error" errmsg = ssf(runtimeOu...
ssf
identifier_name
grade_java.py
import config, json, cgi, sys, Websheet, re, os def grade(reference_solution, student_solution, translate_line, websheet, student):
submission = config.load_submission(student, dep, True) if submission == False: return("Dependency Error", "<div class='dependency-error'><i>Dependency error</i>: " + "You need to successfully complete the <a href='javascript:websheets.load(\""+dep+"\")'><tt>"+dep+"</t...
if not re.match(r"^\w+$", websheet.classname): return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>") dump = { "reference." + websheet.classname : reference_solution, "student." + websheet.classname : student_solution[1], "tester...
identifier_body
grade_java.py
import config, json, cgi, sys, Websheet, re, os def grade(reference_solution, student_solution, translate_line, websheet, student): if not re.match(r"^\w+$", websheet.classname): return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>") dump = { ...
if depws == None: return ("Internal Error", "Dependent websheet " + dep + " does not exist"); submission = config.load_submission(student, dep, True) if submission == False: return("Dependency Error", "<div class='dependency-error'><i>Dependency error</i>: " + ...
random_line_split
0005_auto_20161103_0856.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
('bio', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddFiel...
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('snapventure', '0004_auto_20161102_2043'), ] operations = [ migrations.CreateModel( name='Inscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=Tr...
identifier_body
0005_auto_20161103_0856.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
('location', models.CharField(blank=True, max_length=30)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='inscription', name='user', ...
random_line_split
0005_auto_20161103_0856.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('snapventure', '0004_auto_20161102_2043'), ] operations = [ migrations.CreateModel( name='Inscription', fields=[ ('id', models.AutoField(auto...
Migration
identifier_name
TestWebDAVAccess.py
# $Id: TestWebDAVAccess.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for FileAccess module # import os # Make sure python-kerberos package is installed import kerberos import sys import httplib import urllib2 import urllib2_kerberos import re import base64 import unittest from urlparse import urlparse sys.p...
l2 = f.readline() f.close() self.assertEqual(l1, 'Test creation of file\n', 'Unexpected file content: l1') self.assertEqual(l2, 'Test update of file\n', 'Unexpected file content: l2') return def testRewriteFile(self): filename = mountpoint+'/testRewriteWebDAVFile.t...
f = open(filename,'a+') f.write('Test update of file\n') f.close() f = open(filename,'r') l1 = f.readline()
random_line_split
TestWebDAVAccess.py
# $Id: TestWebDAVAccess.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for FileAccess module # import os # Make sure python-kerberos package is installed import kerberos import sys import httplib import urllib2 import urllib2_kerberos import re import base64 import unittest from urlparse import urlparse sys.p...
# Test cases def testNull(self): assert (True), "True expected" return def testReadMe(self): # Test assumes ADMIRAL shared file system is mounted at mountpoint # Open README file f = open(mountpoint+'/'+readmefile) assert (f), "README file open failed" ...
os.system('umount '+mountpoint) return
identifier_body
TestWebDAVAccess.py
# $Id: TestWebDAVAccess.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for FileAccess module # import os # Make sure python-kerberos package is installed import kerberos import sys import httplib import urllib2 import urllib2_kerberos import re import base64 import unittest from urlparse import urlparse sys.p...
if not hasattr(e, 'code') or e.code != 401: # we got an error - but not a 401 error assert (False), theurl + " Error: " + e authline = e.headers['www-authenticate'] # this gets the www-authenticate line from the headers # which has the authentication scheme and r...
assert (False), theurl + " isn't protected by authentication."
conditional_block
TestWebDAVAccess.py
# $Id: TestWebDAVAccess.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for FileAccess module # import os # Make sure python-kerberos package is installed import kerberos import sys import httplib import urllib2 import urllib2_kerberos import re import base64 import unittest from urlparse import urlparse sys.p...
(self): assert (True) def testPending(self): assert (False), "No pending test" # Assemble test suite from MiscLib import TestUtils def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only ...
testIntegration
identifier_name