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
__init__.py
# Copyright (C) 2015-2020 The Sipwise Team - http://sipwise.com # # 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 distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along ...
random_line_split
ScriptFlowContext.js
Clazz.declarePackage ("JS"); Clazz.load (null, "JS.ScriptFlowContext", ["JS.ScriptCompiler"], function () { c$ = Clazz.decorateAsClass (function () { this.compiler = null; this.token = null; this.pt0 = 0; this.ptDefault = 0; this.$function = null; this.$var = null; this.parent = null; this.lineStart = 0; this.commandSt...
} return "[" + s + "]"; }); Clazz.defineMethod (c$, "setFunction", function ($function) { this.$function = $function; }, "JS.ScriptFunction"); });
s = f.ident + "-" + s; f = f.parent;
random_line_split
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as Command...
#[tokio::test] async fn recover_from_missing_store_contents() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let (local, store, _local_runner_dir) = create_local_runner(); let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let (process, _script_path, _script_dir) = create_sc...
{ let (_, mut workunit) = WorkunitStore::setup_for_tests(); let results = run_roundtrip(1, &mut workunit).await; assert_ne!(results.uncached, results.maybe_cached); assert_eq!(results.uncached.unwrap().exit_code, 1); assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not...
identifier_body
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as Command...
() { let (_, mut workunit) = WorkunitStore::setup_for_tests(); let (local, store, _local_runner_dir) = create_local_runner(); let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let (process, _script_path, _script_dir) = create_script(0); // Run once to cache the process. let first_res...
recover_from_missing_store_contents
identifier_name
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::{RunningWorkunit, WorkunitStore}; use crate::{ CommandRunner as Command...
let (caching, _cache_dir) = create_cached_runner(local, store.clone()); let uncached_result = caching .run(Context::default(), workunit, process.clone().into()) .await; assert_eq!(local_result, uncached_result); // Removing the file means that were the command to be run again without any caching, it ...
.await;
random_line_split
f4m.py
))[0] def read_string(self): res = b'' while True: char = self.read(1) if char == b'\x00': break res += char return res def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_d...
name = 'Seg%d-Frag%d' % (seg_i, frag_i) url = base_url + name frag_filename = '%s-%s' % (tmpfilename, name) success = http_dl.download(frag_filename, {'url': url}) if not success: return False with open(frag_filename, 'rb') as down: ...
conditional_block
f4m.py
""" Reader for Flv files The file format is documented in https://www.adobe.com/devnet/f4v.html """ # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return struct_unpack('!Q', self.read(8))[0] def read_unsigned_int(self): return struct_unp...
(FileDownloader): """ A downloader for f4m manifests or AdobeHDS. """ def real_download(self, filename, info_dict): man_url = info_dict['url'] self.to_screen('[download] Downloading f4m manifest') manifest = self.ydl.urlopen(man_url).read() self.report_destination(filena...
F4mFD
identifier_name
f4m.py
""" Reader for Flv files The file format is documented in https://www.adobe.com/devnet/f4v.html """ # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return struct_unpack('!Q', self.read(8))[0] def read_unsigned_int(self): return struct_unp...
class F4mFD(FileDownloader): """ A downloader for f4m manifests or AdobeHDS. """ def real_download(self, filename, info_dict): man_url = info_dict['url'] self.to_screen('[download] Downloading f4m manifest') manifest = self.ydl.urlopen(man_url).read() self.report_dest...
pass
identifier_body
f4m.py
x00': break res += char return res def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read(4) header_end = 8 ...
self.try_rename(tmpfilename, filename)
random_line_split
Issue.ts
/*class Issue { private number: number;
private title: string; private assignee: Assignee; private labels: Label[]; milestone; constructor() { } render(): string { return '<li id="issue_' + this.number + '" class="issue ' + this.state + '">' + '<span class="number">#' + this.number + '</span>' + '<h4 class="title">...
private state: string;
random_line_split
pygeolib.py
import sys import collections class GeocoderResult(collections.Iterator): """ A geocoder resultset to iterate through address results. Exemple: results = Geocoder.geocode('paris, us') for result in results: print(result.formatted_address, result.location) Provide shortcut to ease fiel...
try: prop = lookup[1] except IndexError: prop = 'long_name' for elem in self.current_data['address_components']: if attribute in elem['types']: return elem[prop] class GeocoderError(Exception): """Base class for errors in the :mod:`pyg...
attribute = GeocoderResult.attribute_mapping[attribute]
conditional_block
pygeolib.py
import sys import collections class GeocoderResult(collections.Iterator): """ A geocoder resultset to iterate through address results. Exemple: results = Geocoder.geocode('paris, us') for result in results: print(result.formatted_address, result.location) Provide shortcut to ease fiel...
(self): return self.current_data['formatted_address'] def __getattr__(self, name): lookup = name.split('__') attribute = lookup[0] if (attribute in GeocoderResult.attribute_mapping): attribute = GeocoderResult.attribute_mapping[attribute] try: prop ...
formatted_address
identifier_name
pygeolib.py
import sys import collections class GeocoderResult(collections.Iterator): """ A geocoder resultset to iterate through address results. Exemple: results = Geocoder.geocode('paris, us') for result in results: print(result.formatted_address, result.location) Provide shortcut to ease fiel...
@property def count(self): return self.len @property def coordinates(self): """ Return a (latitude, longitude) coordinate pair of the current result """ location = self.current_data['geometry']['location'] return location['lat'], location['lng'] @p...
return self.return_next()
identifier_body
pygeolib.py
import sys import collections class GeocoderResult(collections.Iterator): """ A geocoder resultset to iterate through address results. Exemple: results = Geocoder.geocode('paris, us') for result in results: print(result.formatted_address, result.location) Provide shortcut to ease fiel...
return location['lat'], location['lng'] @property def latitude(self): return self.coordinates[0] @property def longitude(self): return self.coordinates[1] @property def raw(self): """ Returns the full result set in dictionary format """ ...
def coordinates(self): """ Return a (latitude, longitude) coordinate pair of the current result """ location = self.current_data['geometry']['location']
random_line_split
j-lyric.test.js
/* global expect test */ const { Lyric } = require('./j-lyric'); async function testLyric(object) { const { url, title, artist, lyricist, composer, arranger, length } = object; const inst = new Lyric(url); await inst.get(); expect(inst.title).toBe(title); expect(inst.artist).toBe(artist); if (lyricist) ex...
length: 734, }); });
random_line_split
j-lyric.test.js
/* global expect test */ const { Lyric } = require('./j-lyric'); async function testLyric(object)
test('', async () => { await testLyric({ url: 'https://j-lyric.net/artist/a002723/l001e83.html', title: 'tune the rainbow', artist: '坂本真綾', lyricist: '岩里祐穂', composer: '菅野よう子', length: 447, }); }); test('', async () => { await testLyric({ url: 'https://j-lyric.net/artist/a000673/l00...
{ const { url, title, artist, lyricist, composer, arranger, length } = object; const inst = new Lyric(url); await inst.get(); expect(inst.title).toBe(title); expect(inst.artist).toBe(artist); if (lyricist) expect(inst.lyricist).toBe(lyricist); if (composer) expect(inst.composer).toBe(composer); if (arr...
identifier_body
j-lyric.test.js
/* global expect test */ const { Lyric } = require('./j-lyric'); async function
(object) { const { url, title, artist, lyricist, composer, arranger, length } = object; const inst = new Lyric(url); await inst.get(); expect(inst.title).toBe(title); expect(inst.artist).toBe(artist); if (lyricist) expect(inst.lyricist).toBe(lyricist); if (composer) expect(inst.composer).toBe(composer); ...
testLyric
identifier_name
detail.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
request, learning_unit_year_id): person = get_object_or_404(Person, user=request.user) context = get_learning_unit_identification_context(learning_unit_year_id, person) learning_unit_year = context['learning_unit_year'] if learning_unit_year.is_external(): template = "learning_unit/external/re...
earning_unit_identification(
identifier_name
detail.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
if not person.user.has_perm(permission): raise PermissionDenied return render(request, template, context)
emplate = "learning_unit/identification.html" permission = 'base.can_access_learningunit'
conditional_block
detail.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
erson = get_object_or_404(Person, user=request.user) context = get_learning_unit_identification_context(learning_unit_year_id, person) learning_unit_year = context['learning_unit_year'] if learning_unit_year.is_external(): template = "learning_unit/external/read.html" permission = 'base.ca...
identifier_body
detail.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
return render(request, template, context)
template = "learning_unit/identification.html" permission = 'base.can_access_learningunit' if not person.user.has_perm(permission): raise PermissionDenied
random_line_split
test_locations_mapping.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that...
c = search.query('match', code='SAXON-PUBLIC').count() assert c == 1
random_line_split
test_locations_mapping.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that...
def test_location_search_mapping(app, locations_records): """Test library search mapping.""" search = LocationsSearch() c = search.query('match', code='MARTIGNY-PUBLIC').count() assert c == 1 c = search.query('match', code='SAXON-PUBLIC').count() assert c == 1
"""Test library elasticsearch mapping.""" search = LocationsSearch() mapping = get_mapping(search.Meta.index) assert mapping loc = Location.create( loc_public_martigny_data, dbcommit=True, reindex=True, delete_pid=True) new_mapping = get_mapping(search.Meta.index) assert mapping == new_m...
identifier_body
test_locations_mapping.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that...
(app, locations_records): """Test library search mapping.""" search = LocationsSearch() c = search.query('match', code='MARTIGNY-PUBLIC').count() assert c == 1 c = search.query('match', code='SAXON-PUBLIC').count() assert c == 1
test_location_search_mapping
identifier_name
user.js
const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String, lowercase: true, unique: true, required: true, }, password: { type: String, required: true, }, }, { timestamps: tru...
user.password = hash; next(); }); }); }); // add method to check password // DO NOT USE ARROW FNS HERE UserSchema.methods.comparePassword = function (candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) { return cb(err); } cb(nu...
{ return next(err); }
conditional_block
user.js
const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String,
required: true, }, password: { type: String, required: true, }, }, { timestamps: true, }); // add pre-hook to salt+hash password on save // DO NOT USE ARROW FNS HERE UserSchema.pre('save', function (next) { const user = this; const SALT_FACTOR = 5; if (!user.isModified('password')) { ret...
lowercase: true, unique: true,
random_line_split
markdownDocument.ts
import * as vscode from 'vscode'; import { MetaData } from './meta'; export class MarkdownDocument { private _document: vscode.TextDocument; private _meta: MetaData; private _content: string; constructor(document: vscode.TextDocument, overrideContent?: string) { this._document = document; ...
) ); else meta = ""; this._meta = new MetaData(meta, this.document.uri); if (!this._content) this._content = this.document.getText( this.document.lineAt(endLine + 1).range.union( this.document.lineAt(this.document.lineCount - 1)...
if (startLine == 0 && endLine > 0) meta = this.document.getText( this.document.lineAt(1).range.union( this.document.lineAt(endLine - 1).range
random_line_split
markdownDocument.ts
import * as vscode from 'vscode'; import { MetaData } from './meta'; export class MarkdownDocument { private _document: vscode.TextDocument; private _meta: MetaData; private _content: string; constructor(document: vscode.TextDocument, overrideContent?: string) { this._document = document; ...
) ); else meta = ""; this._meta = new MetaData(meta, this.document.uri); if (!this._content) this._content = this.document.getText( this.document.lineAt(endLine + 1).range.union( this.document.lineAt(this.document.lineCount - 1)...
{ let meta = ""; let startLine = -1; let endLine = -1; if (this.document.lineAt(0).text == "---") { startLine = 0; for (let i = 1; i < this.document.lineCount; i++) { if (this.document.lineAt(i).text == "---") { endLine = i; ...
identifier_body
markdownDocument.ts
import * as vscode from 'vscode'; import { MetaData } from './meta'; export class MarkdownDocument { private _document: vscode.TextDocument; private _meta: MetaData; private _content: string; constructor(document: vscode.TextDocument, overrideContent?: string) { this._document = document; ...
if (startLine == 0 && endLine > 0) meta = this.document.getText( this.document.lineAt(1).range.union( this.document.lineAt(endLine - 1).range ) ); else meta = ""; this._meta = new MetaData(meta, this.docume...
{ startLine = 0; for (let i = 1; i < this.document.lineCount; i++) { if (this.document.lineAt(i).text == "---") { endLine = i; break; } } if (endLine < 0) startLine = -1; }
conditional_block
markdownDocument.ts
import * as vscode from 'vscode'; import { MetaData } from './meta'; export class MarkdownDocument { private _document: vscode.TextDocument; private _meta: MetaData; private _content: string; constructor(document: vscode.TextDocument, overrideContent?: string) { this._document = document; ...
() { return this._document; } get content() { return this._content; } private load() { let meta = ""; let startLine = -1; let endLine = -1; if (this.document.lineAt(0).text == "---") { startLine = 0; for (let i = 1; i < this.docume...
document
identifier_name
ignore-scripts.js
var test = require("tap").test var npm = require.resolve("../../bin/npm-cli.js") var spawn = require("child_process").spawn var node = process.execPath // ignore-scripts/package.json has scripts that always exit with non-zero error // codes. The "install" script is omitted so that npm tries to run node-gyp, // which ...
(args) { var env = { HOME: process.env.HOME, Path: process.env.PATH, PATH: process.env.PATH } if (process.platform === "win32") env.npm_config_cache = "%APPDATA%\\npm-cache" return spawn(node, args, { cwd: pkg, stdio: "inherit", env: env }) }
createChild
identifier_name
ignore-scripts.js
var test = require("tap").test var npm = require.resolve("../../bin/npm-cli.js") var spawn = require("child_process").spawn var node = process.execPath // ignore-scripts/package.json has scripts that always exit with non-zero error // codes. The "install" script is omitted so that npm tries to run node-gyp, // which ...
test("ignore-scripts: install using the option", function(t) { createChild([npm, "install", "--ignore-scripts"]).on("close", function(code) { t.equal(code, 0) t.end() }) }) test("ignore-scripts: install NOT using the option", function(t) { createChild([npm, "install"]).on("close", function(code) { t....
random_line_split
ignore-scripts.js
var test = require("tap").test var npm = require.resolve("../../bin/npm-cli.js") var spawn = require("child_process").spawn var node = process.execPath // ignore-scripts/package.json has scripts that always exit with non-zero error // codes. The "install" script is omitted so that npm tries to run node-gyp, // which ...
{ var env = { HOME: process.env.HOME, Path: process.env.PATH, PATH: process.env.PATH } if (process.platform === "win32") env.npm_config_cache = "%APPDATA%\\npm-cache" return spawn(node, args, { cwd: pkg, stdio: "inherit", env: env }) }
identifier_body
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
main();
{ // check that the client instance can be created const securityCenterClient = new SecurityCenterClient(); doStuffWithSecurityCenterClient(securityCenterClient); }
identifier_body
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(client: SecurityCenterClient) { client.close(); } function main() { // check that the client instance can be created const securityCenterClient = new SecurityCenterClient(); doStuffWithSecurityCenterClient(securityCenterClient); } main();
doStuffWithSecurityCenterClient
identifier_name
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
doStuffWithSecurityCenterClient(securityCenterClient); } main();
function main() { // check that the client instance can be created const securityCenterClient = new SecurityCenterClient();
random_line_split
pythonpackage.py
.0' % req_maj_ver else: req_majmin_ver = '%s.%s' % (req_maj_ver, req_min_ver) pycode = 'import sys; print("%s.%s" % sys.version_info[:2])' out, _ = run_cmd("%s -c '%s'" % (python_cmd, pycode), simple=False) out = out.strip() # (strict) check ...
"""Initialize custom class variables.""" super(PythonPackage, self).__init__(*args, **kwargs) self.sitecfg = None self.sitecfgfn = 'site.cfg' self.sitecfglibdir = None self.sitecfgincdir = None self.testinstall = False self.testcmd = None self.unp...
random_line_split
pythonpackage.py
command '%s'", cmd) out, ec = run_cmd(cmd, simple=False, force_in_dry_run=True) txt = out.strip().split('\n')[-1] # value obtained should start with specified prefix, otherwise something is very wrong if not txt.startswith(prefix): raise EasyBuildError("Last line of output of %s does not star...
txt = open(self.sitecfgfn).read() self.log.debug("Found %s: %s" % (self.sitecfgfn, txt))
conditional_block
pythonpackage.py
_min_ver, python_cmd) return res def det_pylibdir(plat_specific=False, python_cmd=None): """Determine Python library directory.""" log = fancylogger.getLogger('det_pylibdir', fname=False) if python_cmd is None: # use 'python' that is listed first in $PATH if none was specified python...
"""Prepare for installing Python package.""" super(PythonPackage, self).prerun() self.prepare_python()
identifier_body
pythonpackage.py
res = which(python_cmd) log.debug("Absolute path to retained Python command: %s", res) break else: log.debug("Python command '%s' does not satisfy version requirements (maj: %s, min: %s), moving on", req_maj_ver, req_min_ver, python_cmd) ...
extract_step
identifier_name
du.rs
{ path: PathBuf, is_dir: bool, size: u64, blocks: u64, nlink: u64, created: u64, accessed: u64, modified: u64, } impl Stat { fn new(path: &PathBuf) -> Stat { let metadata = safe_unwrap!(fs::metadata(path)); Stat { path: path.clone(), is_dir: ...
Stat
identifier_name
du.rs
opts.optopt("d", "max-depth", "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize", "N"); // In main opts.optflagopt("", "time", "show time of the last modification of any fi...
random_line_split
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn format_errors(errors: Vec<Error>, source: &str) -> String { let error = errors .into_iter() .map(|err| { match err {
ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) .collect::<Vec<String>>() .join("\n"); format!("Error: {}", error) } #[wasm_bindgen] pub fn transform(data: &str, minify: bool) -> String { match ratel::par...
Error { start, end, .. } => {
random_line_split
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn
(errors: Vec<Error>, source: &str) -> String { let error = errors .into_iter() .map(|err| { match err { Error { start, end, .. } => { ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) ...
format_errors
identifier_name
lib.rs
extern crate ratel; extern crate ratel_codegen; extern crate serde_json; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use ratel::error::{Error, ParseError}; fn format_errors(errors: Vec<Error>, source: &str) -> String
#[wasm_bindgen] pub fn transform(data: &str, minify: bool) -> String { match ratel::parse(&data) { Ok(module) => { ratel_codegen::codegen(&module, minify) }, Err(errors) => format_errors(errors, data) } } #[wasm_bindgen(js_name = generateAST)] pub fn generate_ast(data: &str, minify: bool) -> String { mat...
{ let error = errors .into_iter() .map(|err| { match err { Error { start, end, .. } => { ParseError::UnexpectedToken { start, end, source: source.to_string() } } } }) .map(|err| format!("{}", err)) .collect::<Vec<String>>() .join("\n"); ...
identifier_body
typecheck.ts
/* import * as copy from 'cerebral-addons/copy' import { debounce } from '../../Utils' import { source } from './source' import { SignalType } from '../../context.type' import { sourceAction } from '../actions/sourceAction' import * as unset from 'cerebral-addons/unset' import { update } from '../../Data/actions/update...
] , ignored: [] } ] */
, error: [ copy ( 'input:/errors', 'state:/$editor.errors' ) ] }
random_line_split
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k ...
} None }
{ if let Ok(home) = std::env::var("HOME") { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") { if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgre...
identifier_body
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k ...
} None }
{ return Some(build_from_section(section)); }
conditional_block
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn
(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, ...
build_from_section
identifier_name
lib.rs
use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k ...
if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) =...
{
random_line_split
adminRouter.js
var express = require('express'), router = express.Router(), adminModel = require('../models/adminModel'), moment = require('moment'), helperFun = require('../lib/helperFunc'), md5 = require('md5'); router .get('',function (request,response){ adminModel.find({},{"__v" : 0, "password" : 0, "emailCode" : 0},fun...
admin.password = md5(adminObj.password); admin.username = adminObj.username; admin.firstName = adminObj.firstName; admin.lastName = adminObj.lastName; admin.email = adminObj.email; admin.save(function (error,adminNew){ if(error){ return response.status(500).send({'message' : 'Internal Server...
{ return response.status(400).send({'message' : 'Invalid Password'}).end(); }
conditional_block
adminRouter.js
var express = require('express'), router = express.Router(), adminModel = require('../models/adminModel'), moment = require('moment'), helperFun = require('../lib/helperFunc'), md5 = require('md5'); router .get('',function (request,response){ adminModel.find({},{"__v" : 0, "password" : 0, "emailCode" : 0},fun...
return response.status(500).send({'message' : 'Internal Server error. Please try again later','err' :err}).end(); } response.status(200).send(result).end(); }); }) module.exports = router;
var newAdmin = new adminModel(admin); newAdmin.save(function (err,result){ if(err){
random_line_split
pagelabelscheme.py
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
(): """List of the allowed styles""" return styles.keys() def pdfobjs(self): """Returns a tuple of two elements to insert in the PageLabels.Nums entry of a pdf""" page_num = PdfObject(self.startpage) opts = PdfDict(S=styles[self.style]) if self.prefix != defa...
styles
identifier_name
pagelabelscheme.py
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
return super().__new__(cls, int(startpage), style, str(prefix), int(firstpagenum)) @classmethod def from_pdf(cls, pagenum, opts): """Returns a new PageLabel using options from a pdfrw object""" return cls(pagenum, style=stylecodes.get(opts.S, defaults["style"]), ...
raise ValueError("PageLabel style must be one of %s" % cls.styles())
conditional_block
pagelabelscheme.py
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
opts = PdfDict(S=styles[self.style]) if self.prefix != defaults["prefix"]: opts.P = PdfString.encode(self.prefix) if self.firstpagenum != defaults["firstpagenum"]: opts.St = PdfObject(self.firstpagenum) return page_num, opts
def pdfobjs(self): """Returns a tuple of two elements to insert in the PageLabels.Nums entry of a pdf""" page_num = PdfObject(self.startpage)
random_line_split
pagelabelscheme.py
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
"""Returns a tuple of two elements to insert in the PageLabels.Nums entry of a pdf""" page_num = PdfObject(self.startpage) opts = PdfDict(S=styles[self.style]) if self.prefix != defaults["prefix"]: opts.P = PdfString.encode(self.prefix) if self.firstpagenum != default...
identifier_body
main.rs
plane = Plane::subdivide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile...
{ (ypos * self.tilemap_size[0]) + xpos }
identifier_body
main.rs
: gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData {...
pos: [vertex_x, vertex_y, 0.0], buf_pos: [tilemap_x as f32, tilemap_y as f32] } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32...
VertexData {
random_line_split
main.rs
divide(width, width); // law out the vertices of the plane slice based on the configured tile size information, // setting the a_BufPos vertex data for the vertex shader (that ultimate gets passed through // to the frag shader as a varying, used to determine the "current tile" and the frag's of...
set_tile
identifier_name
main.rs
gfx::TextureSampler<[f32; 4]> = "t_TileSheet", // output out_color: gfx::RenderTarget<ColorFormat> = "Target0", out_depth: gfx::DepthTarget<DepthFormat> = gfx::preset::depth::LESS_EQUAL_WRITE, } } impl TileMapData { pub fn new_empty() -> TileMapData { TileMapData { ...
if self.proj_dirty { encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff); self.proj_dirty = false; } if self.tm_dirty { encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff); self.tm_dirty = false; ...
{ encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap(); }
conditional_block
scroll.js
// Cache selectors var lastId, topMenu = $("#responsive-menu"), topMenuHeight = topMenu.outerHeight()+15, // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function(){ var item = $($(this).attr("href")); if (item.lengt...
var cur = scrollItems.map(function(){ if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length-1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuIt...
// Get id of current scroll item
random_line_split
scroll.js
// Cache selectors var lastId, topMenu = $("#responsive-menu"), topMenuHeight = topMenu.outerHeight()+15, // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function(){ var item = $($(this).attr("href")); if (item.lengt...
});
{ lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href='#"+id+"']").parent().addClass("active"); }
conditional_block
test_result.py
# coding: utf-8 from orgprobe.result import Result import logging def
(): title = u"Some text here with a \u00a3 sign" r = Result('ok', 200, title=title) assert isinstance(title, unicode) assert r.title == "Some text here with a £ sign" assert isinstance(r.title, str) assert str(r) == """<Result: status="ok" code="200" category="None" type="None" ip="None" body_l...
test_unicode
identifier_name
test_result.py
# coding: utf-8 from orgprobe.result import Result import logging def test_unicode():
def test_utf8(): r = Result('ok', 200, title="£20") assert r.title == "£20" assert isinstance(r.title, str) assert str(r) == """<Result: status="ok" code="200" category="None" type="None" ip="None" body_length="0" """ \ """ssl_verified="None" ssl_fingerprint="None" final_url="None" resolved_ip...
title = u"Some text here with a \u00a3 sign" r = Result('ok', 200, title=title) assert isinstance(title, unicode) assert r.title == "Some text here with a £ sign" assert isinstance(r.title, str) assert str(r) == """<Result: status="ok" code="200" category="None" type="None" ip="None" body_length="0...
identifier_body
test_result.py
# coding: utf-8 from orgprobe.result import Result import logging
r = Result('ok', 200, title=title) assert isinstance(title, unicode) assert r.title == "Some text here with a £ sign" assert isinstance(r.title, str) assert str(r) == """<Result: status="ok" code="200" category="None" type="None" ip="None" body_length="0" """ \ """ssl_verified="None" ssl_fi...
def test_unicode(): title = u"Some text here with a \u00a3 sign"
random_line_split
space2comment.py
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def dependencies(): pass def tamper(payload, **kwargs): """ Replaces space character (' ') with ...
elif payload[i] == " " and not doublequote and not quote: retVal += "/**/" continue retVal += payload[i] return retVal
doublequote = not doublequote
conditional_block
space2comment.py
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def dependencies(): pass def tamper(payload, **kwargs):
quote, doublequote, firstspace = False, False, False for i in xrange(len(payload)): if not firstspace: if payload[i].isspace(): firstspace = True retVal += "/**/" continue elif payload[i] == '\'': ...
""" Replaces space character (' ') with comments '/**/' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 * Oracle 10g * PostgreSQL 8.3, 8.4, 9.0 Notes: * Useful to bypass weak and bespoke web application firewalls >>> tamper('SELECT id FROM us...
identifier_body
space2comment.py
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def dependencies(): pass def tamper(payload, **kwargs): """ Replaces space character (' ') with ...
firstspace = True retVal += "/**/" continue elif payload[i] == '\'': quote = not quote elif payload[i] == '"': doublequote = not doublequote elif payload[i] == " " and not doublequote and n...
if not firstspace: if payload[i].isspace():
random_line_split
space2comment.py
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def
(): pass def tamper(payload, **kwargs): """ Replaces space character (' ') with comments '/**/' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 * Oracle 10g * PostgreSQL 8.3, 8.4, 9.0 Notes: * Useful to bypass weak and bespoke web applica...
dependencies
identifier_name
Pdu7930.py
###################################################################### # # Pdu7930 object class # ###################################################################### from Globals import InitializeClass from Products.ZenRelations.RelSchema import * from Products.ZenModel.Device import Device from Products.ZenModel.Z...
def __init__(self, *args, **kw): Device.__init__(self, *args, **kw) self.buildRelations() InitializeClass(Pdu7930)
random_line_split
Pdu7930.py
###################################################################### # # Pdu7930 object class # ###################################################################### from Globals import InitializeClass from Products.ZenRelations.RelSchema import * from Products.ZenModel.Device import Device from Products.ZenModel.Z...
InitializeClass(Pdu7930)
Device.__init__(self, *args, **kw) self.buildRelations()
identifier_body
Pdu7930.py
###################################################################### # # Pdu7930 object class # ###################################################################### from Globals import InitializeClass from Products.ZenRelations.RelSchema import * from Products.ZenModel.Device import Device from Products.ZenModel.Z...
(self, *args, **kw): Device.__init__(self, *args, **kw) self.buildRelations() InitializeClass(Pdu7930)
__init__
identifier_name
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use crate::dom::b...
} #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1...
random_line_split
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use crate::dom::b...
#[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1 ...
{ self.client.get_controller() }
identifier_body
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use crate::dom::b...
{ eventtarget: EventTarget, controller: MutNullableDom<ServiceWorker>, client: Dom<Client>, } impl ServiceWorkerContainer { fn new_inherited(client: &Client) -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Defa...
ServiceWorkerContainer
identifier_name
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use crate::dom::b...
, } // B: Step 3 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type( "Script URL contains forbidden characters".to_owned(), )); ...
{ promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; }
conditional_block
KeyProcessorService.ts
/*! * MiracleDevs.Angular v1.0.0 * Copyright (c) 2017 Miracle Devs, Inc * Licensed under MIT (https://github.com/MiracleDevs/MiracleDevs.Angular/blob/master/LICENSE) */ ///<reference path="../../typings/index.d.ts"/> ///<reference path="../core/ArrayList.ts" /> ///<reference path="../interfaces/IServiceRegister....
ext: string): ArrayList<KeyAction> { const keyActions = new ArrayList<KeyAction>(); const actionStrings = text.split("|"); for (let i = 0; i < actionStrings.length; i++) { const keyAction = new KeyAction(); const actionString = act...
rseActions(t
identifier_name
KeyProcessorService.ts
/*! * MiracleDevs.Angular v1.0.0 * Copyright (c) 2017 Miracle Devs, Inc * Licensed under MIT (https://github.com/MiracleDevs/MiracleDevs.Angular/blob/master/LICENSE) */ ///<reference path="../../typings/index.d.ts"/> ///<reference path="../core/ArrayList.ts" /> ///<reference path="../interfaces/IServiceRegister....
keyActions.add(keyAction); } return keyActions; } static factory(parse: IParseService): IKeyProcessorService { return new KeyProcessorService(parse); } } //////////////////////////////////////////////////////////// // Reg...
if (parameters.any(x => x === "alt")) keyAction.alt = true; else if (parameters.any(x => x === "!alt")) keyAction.alt = false;
random_line_split
optuna_example.py
"""This test checks that Optuna is functional. It also checks that it is usable with a separate scheduler. """ import time import ray from ray import tune from ray.tune.suggest import ConcurrencyLimiter from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.optuna import OptunaSearch
return (0.1 + width * step / 100)**(-1) + height * 0.1 def easy_objective(config): # Hyperparameters width, height = config["width"], config["height"] for step in range(config["steps"]): # Iterative training function - can be any arbitrary training procedure intermediate_score = evalu...
def evaluation_fn(step, width, height):
random_line_split
optuna_example.py
"""This test checks that Optuna is functional. It also checks that it is usable with a separate scheduler. """ import time import ray from ray import tune from ray.tune.suggest import ConcurrencyLimiter from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.optuna import OptunaSearch def eval...
scheduler = AsyncHyperBandScheduler() tune.run( easy_objective, metric="mean_loss", mode="min", search_alg=algo, scheduler=scheduler, **tune_kwargs)
import argparse parser = argparse.ArgumentParser() parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing") args, _ = parser.parse_known_args() ray.init(configure_logging=False) tune_kwargs = { "num_samples": 10 if args.smoke_test else 100, ...
conditional_block
optuna_example.py
"""This test checks that Optuna is functional. It also checks that it is usable with a separate scheduler. """ import time import ray from ray import tune from ray.tune.suggest import ConcurrencyLimiter from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.optuna import OptunaSearch def eval...
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing") args, _ = parser.parse_known_args() ray.init(configure_logging=False) tune_kwargs = { "num_samples": 10 ...
width, height = config["width"], config["height"] for step in range(config["steps"]): # Iterative training function - can be any arbitrary training procedure intermediate_score = evaluation_fn(step, width, height) # Feed the score back back to Tune. tune.report(iterations=step, mean...
identifier_body
optuna_example.py
"""This test checks that Optuna is functional. It also checks that it is usable with a separate scheduler. """ import time import ray from ray import tune from ray.tune.suggest import ConcurrencyLimiter from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.optuna import OptunaSearch def
(step, width, height): return (0.1 + width * step / 100)**(-1) + height * 0.1 def easy_objective(config): # Hyperparameters width, height = config["width"], config["height"] for step in range(config["steps"]): # Iterative training function - can be any arbitrary training procedure int...
evaluation_fn
identifier_name
midnight_caravan_superscraper.js
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(...
for(var i=0; i < blocks.length; i++) { var episodeDescription = blocks[i].html.split('<p>')[0]; var episodeNumber = /Ep. (\d+) /.exec(episodeDescription)[1]; var mp3RegexMatches = /(http.+\.mp3)\".+>(.+) \(Full MP3\)/.exec(episodeBlocks[i].html); var mp3FileUrl = mp3RegexMatches[1]; episodes....
{ casper.exit("Oh noes."); }
conditional_block
midnight_caravan_superscraper.js
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(...
(url, file) { var mp3Filepath = mp3Folder + file; if(!fs.exists(mp3Filepath)) { casper.download(url, mp3Filepath); } } casper.then(function () { casper.fillSelectors('#wma_login_form', { '#user_login': config.username, '#user_pass': config.password }); casper.click('#wp-submit'); }); casper....
downloadEpisode
identifier_name
midnight_caravan_superscraper.js
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(...
}); downloadEpisode(mp3FileUrl, 'episode_' + episodeNumber + '.mp3'); } casper.echo(JSON.stringify(episodes)); }); casper.run();
random_line_split
midnight_caravan_superscraper.js
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(...
casper.then(function () { casper.fillSelectors('#wma_login_form', { '#user_login': config.username, '#user_pass': config.password }); casper.click('#wp-submit'); }); casper.thenOpen(currentMonthUrl); casper.then(function () { var blocks = casper.getElementsInfo('div.content-column'); var episodeBl...
{ var mp3Filepath = mp3Folder + file; if(!fs.exists(mp3Filepath)) { casper.download(url, mp3Filepath); } }
identifier_body
image.py
from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def imread(filename, imread=None, preprocess=None):
>>> im.shape # doctest: +SKIP (365, 1000, 1000, 3) Returns ------- Dask array of all images stacked along the first dimension. All images will be treated as individual chunks """ imread = imread or sk_imread filenames = sorted(glob(filename)) if not filenames: raise V...
""" Read a stack of images into a dask array Parameters ---------- filename: string A globstring like 'myfile.*.png' imread: function (optional) Optionally provide custom imread function. Function should expect a filename and produce a numpy array. Defaults to ``skimage...
identifier_body
image.py
from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def
(filename, imread=None, preprocess=None): """ Read a stack of images into a dask array Parameters ---------- filename: string A globstring like 'myfile.*.png' imread: function (optional) Optionally provide custom imread function. Function should expect a filename and produc...
imread
identifier_name
image.py
from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def imread(filename, imread=None, preprocess=None): """ Read a stack of images into a dask a...
>>> im.shape # doctest: +SKIP (365, 1000, 1000, 3) Returns ------- Dask array of all images stacked along the first dimension. All images will be treated as individual chunks """ imread = imread or sk_imread filenames = sorted(glob(filename)) if not filenames: raise V...
>>> from dask.array.image import imread >>> im = imread('2015-*-*.png') # doctest: +SKIP
random_line_split
image.py
from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def imread(filename, imread=None, preprocess=None): """ Read a stack of images into a dask a...
keys = [(name, i) + (0,) * len(sample.shape) for i in range(len(filenames))] if preprocess: values = [(add_leading_dimension, (preprocess, (imread, filename))) for filename in filenames] else: values = [(add_leading_dimension, (imread, filename)) for fil...
sample = preprocess(sample)
conditional_block
utilities.py
'''Simple utility functions that should really be in a C module''' from math import * from OpenGLContext.arrays import * from OpenGLContext import vectorutilities def rotMatrix( (x,y,z,a) ): """Given rotation as x,y,z,a (a in radians), return rotation matrix Returns a 4x4 rotation matrix for the given rotatio...
def magnitude( vector ): """Given a 3 or 4-item vector, return the vector's magnitude""" return vectorutilities.magnitude( vector[:3] )[0] def normalise( vector ): """Given a 3 or 4-item vector, return a 3-item unit vector""" return vectorutilities.normalise( vector[:3] )[0] def pointNormal2Plane( poi...
"""Given 2 4-item vectors, return the cross product as a 4-item vector""" x,y,z = vectorutilities.crossProduct( first, second )[0] return [x,y,z,0]
identifier_body
utilities.py
'''Simple utility functions that should really be in a C module''' from math import * from OpenGLContext.arrays import * from OpenGLContext import vectorutilities def rotMatrix( (x,y,z,a) ): """Given rotation as x,y,z,a (a in radians), return rotation matrix Returns a 4x4 rotation matrix for the given rotatio...
if len(points) < 4: return True a,b = points[:2] vec1 = reshape(b-a,(1,3)) rest = points[2:] - b vecs = vectorutilities.crossProduct( rest, vec1, ) vecsNonZero = sometrue(vecs,1) vecs = compress(vecsNonZero, vecs,0) if not len(vecs): return True ve...
points = asarray( points, 'f' )
random_line_split
utilities.py
'''Simple utility functions that should really be in a C module''' from math import * from OpenGLContext.arrays import * from OpenGLContext import vectorutilities def rotMatrix( (x,y,z,a) ): """Given rotation as x,y,z,a (a in radians), return rotation matrix Returns a 4x4 rotation matrix for the given rotatio...
( first, second ): """Given 2 4-item vectors, return the cross product as a 4-item vector""" x,y,z = vectorutilities.crossProduct( first, second )[0] return [x,y,z,0] def magnitude( vector ): """Given a 3 or 4-item vector, return the vector's magnitude""" return vectorutilities.magnitude( vector[:3]...
crossProduct
identifier_name
utilities.py
'''Simple utility functions that should really be in a C module''' from math import * from OpenGLContext.arrays import * from OpenGLContext import vectorutilities def rotMatrix( (x,y,z,a) ): """Given rotation as x,y,z,a (a in radians), return rotation matrix Returns a 4x4 rotation matrix for the given rotatio...
else: final = sum(normals,0) x,y,z = final if x == y == z == 0.0: x,y,z = normals[0] if x or y: x,y,z = -x,-y,z else: x,y,z = -x,y,-z return normalise( (x,y,z) ) def coplanar( points ): """Determine if points are coplanar All sets of poi...
weights = reshape(asarray( weights, 'f'),(len(weights),1)) final = sum(normals*weights, 0)
conditional_block
utils.py
import threading import numpy as np def ros_ensure_valid_name(name): return name.replace('-','_') def lineseg_box(xmin, ymin, xmax, ymax): return [ [xmin,ymin,xmin,ymax], [xmin,ymax,xmax,ymax], [xmax,ymax,xmax,ymin], [xmax,ymin,xmin,ymin], ] def lineseg_circle(x,y,...
self.lock.acquire() try: self._val = new_value finally: self.lock.release()
finally: self.lock.release() return val def set(self,new_value):
random_line_split
utils.py
import threading import numpy as np def ros_ensure_valid_name(name): return name.replace('-','_') def lineseg_box(xmin, ymin, xmax, ymax): return [ [xmin,ymin,xmin,ymax], [xmin,ymax,xmax,ymax], [xmax,ymax,xmax,ymin], [xmax,ymin,xmin,ymin], ] def lineseg_circle(x,y,...
draw_linesegs.append( (xdraw[-1],ydraw[-1],xdraw[0],ydraw[0])) return draw_linesegs class SharedValue: def __init__(self): self.evt = threading.Event() self._val = None def set(self,value): # called from producer thread self._val = value self.evt.set()...
draw_linesegs.append( (xdraw[i],ydraw[i],xdraw[i+1],ydraw[i+1]))
conditional_block
utils.py
import threading import numpy as np def ros_ensure_valid_name(name): return name.replace('-','_') def lineseg_box(xmin, ymin, xmax, ymax): return [ [xmin,ymin,xmin,ymax], [xmin,ymax,xmax,ymax], [xmax,ymax,xmax,ymin], [xmax,ymin,xmin,ymin], ] def lineseg_circle(x,y,...
(self): self.lock.acquire() try: val = self._val finally: self.lock.release() return val def set(self,new_value): self.lock.acquire() try: self._val = new_value finally: self.lock.release()
get
identifier_name
utils.py
import threading import numpy as np def ros_ensure_valid_name(name): return name.replace('-','_') def lineseg_box(xmin, ymin, xmax, ymax): return [ [xmin,ymin,xmin,ymax], [xmin,ymax,xmax,ymax], [xmax,ymax,xmax,ymin], [xmax,ymin,xmin,ymin], ] def lineseg_circle(x,y,...
def get_nowait(self): # XXX TODO this is not atomic and is thus dangerous. # (The value could get read, then another thread could set it, # and only then might it get flagged as clear by this thread, # even though a new value is waiting.) val = self._val self.evt.cle...
self.evt.wait(*args,**kwargs) val = self._val self.evt.clear() return val
identifier_body
fact.rs
#[allow(non_snake_case)] #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ExprItem { pub data: Option<String>, // pub type: Option<String>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct FactcContent { pub expr: Option<Vec<ExprItem>>, } #[derive(RustcDecodable, RustcEnc...
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct Fact { pub fact: FactBody, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ObjectsFactBody { pub paging: super::MetadataPaging, pub items: Vec<Fact>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct...
pub meta: super::MetadataMeta, }
random_line_split
fact.rs
#[allow(non_snake_case)] #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct ExprItem { pub data: Option<String>, // pub type: Option<String>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct
{ pub expr: Option<Vec<ExprItem>>, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct FactBody { pub content: FactcContent, pub meta: super::MetadataMeta, } #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub struct Fact { pub fact: FactBody, } #[derive(RustcDecodable, Rust...
FactcContent
identifier_name