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
EventListener.js
/** * Created by vladi on 27-Jan-17. */ import { removeEventListenerById, suspendEventListenerById, restoreEventListenerById, isListenerSuspended, listenerExists, addTypeFilter, addTypeFilters, resetTypeFilter, removeTypeFilter, removeTypeFilters } from './EventsControl'; expor...
() { suspendEventListenerById(this.listenerUid); return this; } restore() { restoreEventListenerById(this.listenerUid); return this; } isSuspended() { return isListenerSuspended(this.listenerUid); } isRemoved() { return !listenerExists(this.list...
suspend
identifier_name
test00002.test.ts
import { getMessageManager, getQueueManagerFrontend, produceAndAcknowledgeMessage, } from '../common'; import { promisifyAll } from 'bluebird'; test('Combined test. Requeue message from acknowledged queue. Check both pending and acknowledged messages. Check queue metrics.', async () => { const { consumer, queu...
const res5 = await messageManager.getPendingMessagesAsync(queue, 0, 100); expect(res5.total).toBe(1); expect(res5.items.length).toBe(1); expect(res5.items[0].message.getId()).toEqual(message.getRequiredId()); const res6 = await messageManager.getAcknowledgedMessagesAsync(queue, 0, 100); expect(res6.total)...
undefined, );
random_line_split
plugin.py
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### import re import time import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import s...
try: (when, said) = db.seen(channel, '<last>') irc.reply(format('Someone was last seen in %s %s ago: %s', channel, utils.timeElapsed(time.time()-when), said)) except KeyError: irc.reply('I have never seen anyo...
db = self.db
conditional_block
plugin.py
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### import re import time import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import supybot....
(self, channel, nickOrId): return self[channel, nickOrId] filename = conf.supybot.directories.data.dirize('Seen.db') anyfilename = conf.supybot.directories.data.dirize('Seen.any.db') class Seen(callbacks.Plugin): noIgnore = True def __init__(self, irc): self.__parent = super(Seen, self) ...
seen
identifier_name
plugin.py
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### import re import time import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import supybot....
doTopic = doMode def _seen(self, irc, channel, name, any=False): if any: db = self.anydb else: db = self.db try: results = [] if '*' in name: results = db.seenWildcard(channel, name) else: resul...
if msg.nick: self.doQuit(irc, msg)
identifier_body
plugin.py
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### import re import time import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import supybot....
def last(self, irc, msg, args, channel): """[<channel>] Returns the last thing said
except KeyError: irc.reply('I have never seen anyone.')
random_line_split
setup.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Stores the Twig configuration. use std::path::Path; use std::rc::Rc; use extension; use extension::api::Extension; use engine::{Engine, options, Option...
/// An absolute path where to store the compiled templates (optional) pub fn set_cache(mut self, cache: Option<&Path>) -> Self { self.opt.cache = cache.map(|reference| reference.to_owned()); self } /// Whether to reload the template if the original source changed (optional). /// ...
{ self.opt.autoescape = autoescape; self }
identifier_body
setup.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Stores the Twig configuration. use std::path::Path; use std::rc::Rc; use extension; use extension::api::Extension; use engine::{Engine, options, Option...
(mut self, auto_reload: Option<bool>) -> Self { self.opt.auto_reload = auto_reload; self } /// A flag that indicates whether optimizations are applied pub fn set_optimizations(mut self, optimizations: options::Optimizations) -> Self { self.opt.optimizations = optimizations; ...
set_auto_reload
identifier_name
setup.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Stores the Twig configuration. use std::path::Path; use std::rc::Rc; use extension; use extension::api::Extension; use engine::{Engine, options, Option...
// } }
random_line_split
convert_docx.py
#https://python-docx.readthedocs.io/en/latest/user/install.html #python-docx may be installed with pip if you have it available: # pip install python-docx #python-docx can also be installed using easy_install, although this is #discouraged: # easy_install python-docx #If neither pip nor easy_install is available, it...
# the assignee should come 1st assgn.assignee = students[0].strip() if len(students) > 1: # the householder second # '> 1' in case there is an additinal helper (will be ignored) assgn.hholder = students[1].strip() assignments.append( assgn ) ...
# be sure to strip each element of the array `students` in case split leaves white space students = participants.split('\n') # assume at most 2 elements, and at least one
random_line_split
convert_docx.py
#https://python-docx.readthedocs.io/en/latest/user/install.html #python-docx may be installed with pip if you have it available: # pip install python-docx #python-docx can also be installed using easy_install, although this is #discouraged: # easy_install python-docx #If neither pip nor easy_install is available, it...
if len(students) > 1: # the householder second # '> 1' in case there is an additinal helper (will be ignored) assgn.hholder = students[1].strip() assignments.append( assgn ) # the same for the second participants = row.cells[SECTION_B_PARTICIPANTS]....
'''parse an assignment row from table, returns an array with the assignments''' assignments = [] # participants for first assgn participants = row.cells[SECTION_A_PARTICIPANTS].text.strip() if participants != '': # if there are participants assgn = Assignment() # new empty assignment ...
identifier_body
convert_docx.py
#https://python-docx.readthedocs.io/en/latest/user/install.html #python-docx may be installed with pip if you have it available: # pip install python-docx #python-docx can also be installed using easy_install, although this is #discouraged: # easy_install python-docx #If neither pip nor easy_install is available, it...
(weekHeaderRow, year, month): '''extract the date from the date row from table''' raw_date = weekHeaderRow.cells[DATE].text.strip() if raw_date == '': return raw_date # convert to nice date format # split up to look for a number for the day of the month date_parts = raw_da...
getWeekDate
identifier_name
convert_docx.py
#https://python-docx.readthedocs.io/en/latest/user/install.html #python-docx may be installed with pip if you have it available: # pip install python-docx #python-docx can also be installed using easy_install, although this is #discouraged: # easy_install python-docx #If neither pip nor easy_install is available, it...
# convert to nice date format # split up to look for a number for the day of the month date_parts = raw_date.split() # list comprehension to select numbeic strings numericParts = [part for part in date_parts if part.isnumeric()] # assume there will only be one day = int( nume...
return raw_date
conditional_block
episode.ts
file exist.. */ function fileExist(path: string) { try { fs.statSync(path); return true; } catch (e) { return false; } } function sanitiseFileName(str: string) { const sanitized = str.replace(/[\/':\?\*"<>\\\.\|]/g, '_'); return sanitized.replace(/{DIR_SEPARATOR}/g, '/'); } /** * Downl...
(value: number|string, length: number) { let valueString = (typeof value !== 'string') ? String(value) : value; while (valueString.length < length) { valueString = '0' + valueString; } return valueString; } /** * Requests the page data and scrapes the id, episode, series and swf. */ function scrapePa...
prefix
identifier_name
episode.ts
file exist.. */ function fileExist(path: string)
function sanitiseFileName(str: string) { const sanitized = str.replace(/[\/':\?\*"<>\\\.\|]/g, '_'); return sanitized.replace(/{DIR_SEPARATOR}/g, '/'); } /** * Downloads the subtitle and video. */ function download(config: IConfig, page: IEpisodePage, player: IEpisodePlayer, done: (err: Error | string, ign: b...
{ try { fs.statSync(path); return true; } catch (e) { return false; } }
identifier_body
episode.ts
'Error...', true); return done(errDS, false); } const now = Date.now(); if ( ((page.media === null) && (player.video.file !== undefined)) || ((page.media !== null) /* Do they still create page in advance for unreleased episodes? */) ) { log.dispEpisode(fileName, 'Fetchi...
log.dumpToDebug('episode unexpected', look); } do
conditional_block
episode.ts
a file exist.. */ function fileExist(path: string) { try { fs.statSync(path); return true; } catch (e) { return false; } } function sanitiseFileName(str: string) { const sanitized = str.replace(/[\/':\?\*"<>\\\.\|]/g, '_'); return sanitized.replace(/{DIR_SEPARATOR}/g, '/'); } /** * Dow...
let j; /* Find a proper subtitles */ for (j = 0; j < config.sublang.length; j++) { const reqSubLang = config.sublang[j]; for (i = 0; i < subs.length; i++) { const curSub = subs[i]; if (curSub.format === 'ass' && curSub.language === reqSubLang) { my_re...
random_line_split
mac_securityd.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
"""Formatter for ASL Securityd file.""" DATA_TYPE = 'mac:asl:securityd:line' FORMAT_STRING_PIECES = [ u'Sender: {sender}', u'({sender_pid})', u'Level: {level}', u'Facility: {facility}', u'Text: {message}'] FORMAT_STRING_SHORT_PIECES = [u'Text: {message}'] SOURCE_LONG = 'Mac ASL...
identifier_body
mac_securityd.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License");
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Lic...
# you may not use this file except in compliance with the License.
random_line_split
mac_securityd.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
(interface.ConditionalEventFormatter): """Formatter for ASL Securityd file.""" DATA_TYPE = 'mac:asl:securityd:line' FORMAT_STRING_PIECES = [ u'Sender: {sender}', u'({sender_pid})', u'Level: {level}', u'Facility: {facility}', u'Text: {message}'] FORMAT_STRING_SHORT_PIECES = [u'Te...
MacSecuritydLogFormatter
identifier_name
bbox.rs
//! Bounding boxes that know their coordinate space. use crate::coord_units::CoordUnits; use crate::rect::Rect; use crate::transform::Transform; #[derive(Debug, Default, Copy, Clone)] pub struct BoundingBox { transform: Transform, pub rect: Option<Rect>, // without stroke pub ink_rect: Option<Rect>, /...
r1: Option<Rect>, r2: Option<Rect>, transform: &Transform, clip: bool, ) -> Option<Rect> { match (r1, r2, clip) { (r1, None, _) => r1, (None, Some(r2), _) => Some(transform.transform_rect(&r2)), (Some(r1), Some(r2), true) => transform .transform_rect(&r2) ...
} fn combine_rects(
random_line_split
bbox.rs
//! Bounding boxes that know their coordinate space. use crate::coord_units::CoordUnits; use crate::rect::Rect; use crate::transform::Transform; #[derive(Debug, Default, Copy, Clone)] pub struct BoundingBox { transform: Transform, pub rect: Option<Rect>, // without stroke pub ink_rect: Option<Rect>, /...
(mut self) { self.rect = None; self.ink_rect = None; } fn combine(&mut self, src: &BoundingBox, clip: bool) { if src.rect.is_none() && src.ink_rect.is_none() { return; } // this will panic!() if it's not invertible... should we check on our own? let ...
clear
identifier_name
bbox.rs
//! Bounding boxes that know their coordinate space. use crate::coord_units::CoordUnits; use crate::rect::Rect; use crate::transform::Transform; #[derive(Debug, Default, Copy, Clone)] pub struct BoundingBox { transform: Transform, pub rect: Option<Rect>, // without stroke pub ink_rect: Option<Rect>, /...
pub fn with_ink_rect(self, ink_rect: Rect) -> BoundingBox { BoundingBox { ink_rect: Some(ink_rect), ..self } } pub fn clear(mut self) { self.rect = None; self.ink_rect = None; } fn combine(&mut self, src: &BoundingBox, clip: bool) { ...
{ BoundingBox { rect: Some(rect), ..self } }
identifier_body
test_admin_actions.py
# -*- coding: utf-8 -*- import django_dynamic_fixture as fixture from unittest import mock from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase from readthedocs.core.models import UserProfile from readthedocs....
(self): self.client.force_login(self.admin) def test_project_ban_owner(self): self.assertFalse(self.owner.profile.banned) action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'ban_owner', 'index': 0, } resp = self.client.post...
setUp
identifier_name
test_admin_actions.py
# -*- coding: utf-8 -*- import django_dynamic_fixture as fixture from unittest import mock from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase from readthedocs.core.models import UserProfile from readthedocs....
def setUp(self): self.client.force_login(self.admin) def test_project_ban_owner(self): self.assertFalse(self.owner.profile.banned) action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'ban_owner', 'index': 0, } resp = s...
cls.owner = fixture.get(User) cls.profile = fixture.get(UserProfile, user=cls.owner, banned=False) cls.admin = fixture.get(User, is_staff=True, is_superuser=True) cls.project = fixture.get( Project, main_language_project=None, users=[cls.owner], )
identifier_body
test_admin_actions.py
# -*- coding: utf-8 -*- import django_dynamic_fixture as fixture from unittest import mock from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase from readthedocs.core.models import UserProfile from readthedocs....
@mock.patch('readthedocs.projects.admin.clean_project_resources') def test_project_delete(self, clean_project_resources): """Test project and artifacts are removed.""" action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'delete_selected', 'inde...
) self.assertFalse(self.project.users.filter(profile__banned=True).exists()) self.assertEqual(self.project.users.filter(profile__banned=False).count(), 2)
random_line_split
solar_graph.py
""" Created on September 20, 2011 @author: sbobovyc """ """ Copyright (C) 2011 Stanislav Bobovych 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, ...
print self.current_sample_stride print "##################" def plot(self, xmin=None, xmax=None): self.ax.set_title(self.title) self.ax.get_xaxis().set_label_text(self.xlabel) self.ax.get_yaxis().set_label_text(self.ylabel) self.ax.grid(...
self.solar_data = solar_data self.figure = fig self.ax = ax self.original_sample_stride = sample_stride self.current_sample_stride = sample_stride self.title = title self.xlabel = xlabel self.ylabel = ylabel self.xdata = xdata self.ydata =...
identifier_body
solar_graph.py
""" Created on September 20, 2011 @author: sbobovyc """ """ Copyright (C) 2011 Stanislav Bobovych 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, ...
else: ydata = row[self.ydata] if (xdata >= xmin and xdata <= xmax) or (xmin == None and xmax == None): self.ax.scatter( float(xdata), float(ydata) ) counter += 1 # print xdata, " ", float(row[self.ydata]) self.ax.autosc...
random_line_split
solar_graph.py
""" Created on September 20, 2011 @author: sbobovyc """ """ Copyright (C) 2011 Stanislav Bobovych 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, ...
if (xdata >= xmin and xdata <= xmax) or (xmin == None and xmax == None): self.ax.scatter( float(xdata), float(ydata) ) counter += 1 # print xdata, " ", float(row[self.ydata]) self.ax.autoscale_view(scalex=False,scaley=True) print "Plotted...
ydata = row[self.ydata]
conditional_block
solar_graph.py
""" Created on September 20, 2011 @author: sbobovyc """ """ Copyright (C) 2011 Stanislav Bobovych 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, ...
(self): new_delta_x = self.ax.get_xlim()[1] - self.ax.get_xlim()[0] self.current_sample_stride = int( ( self.original_sample_stride * new_delta_x ) / self.original_delta_x ) if self.current_sample_stride == 0: self.current_sample_stride = 1 ## # @param ax: matplotlib axes, ne...
calc_stride
identifier_name
links.rs
use std::collections::HashMap; use core::PackageSet; use util::{CargoResult, human}; // Validate that there are no duplicated native libraries among packages and // that all packages with `links` also have a build script. pub fn
(deps: &PackageSet) -> CargoResult<()> { let mut map = HashMap::new(); for dep in deps.iter() { let lib = match dep.manifest().links() { Some(lib) => lib, None => continue, }; match map.get(&lib) { Some(previous) => { return Err(human(...
validate
identifier_name
links.rs
use std::collections::HashMap; use core::PackageSet; use util::{CargoResult, human}; // Validate that there are no duplicated native libraries among packages and // that all packages with `links` also have a build script. pub fn validate(deps: &PackageSet) -> CargoResult<()> { let mut map = HashMap::new(); f...
}
random_line_split
links.rs
use std::collections::HashMap; use core::PackageSet; use util::{CargoResult, human}; // Validate that there are no duplicated native libraries among packages and // that all packages with `links` also have a build script. pub fn validate(deps: &PackageSet) -> CargoResult<()>
`{}` but does not have a custom build \ script", dep.package_id(), lib))) } map.insert(lib, dep.package_id()); } Ok(()) }
{ let mut map = HashMap::new(); for dep in deps.iter() { let lib = match dep.manifest().links() { Some(lib) => lib, None => continue, }; match map.get(&lib) { Some(previous) => { return Err(human(format!("native library `{}` is being l...
identifier_body
writebatch.rs
use utils::{tmpdir}; use leveldb::database::{Database}; use leveldb::options::{Options,ReadOptions,WriteOptions}; use leveldb::database::kv::{KV}; use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator}; #[test] fn test_writebatch() { let mut opts = Options::new(); opts.create_if_missing = true; ...
{ put: i32, deleted: i32, } impl WritebatchIterator for Iter { type K = i32; fn put(&mut self, _key: i32, _value: &[u8]) { self.put = self.put + 1; } fn deleted(&mut self, _key: i32) { self.deleted = self.deleted + 1; } } #[test] fn t...
Iter
identifier_name
writebatch.rs
use utils::{tmpdir}; use leveldb::database::{Database}; use leveldb::options::{Options,ReadOptions,WriteOptions}; use leveldb::database::kv::{KV}; use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator}; #[test] fn test_writebatch() { let mut opts = Options::new(); opts.create_if_missing = true; ...
} let read_opts2 = ReadOptions::new(); let res2 = database.get(read_opts2, 1); match res2 { Ok(data) => { assert!(data.is_none()) }, Err(_) => { panic!("failed reading data") } } } struct Iter { put: i32, deleted: i32, } impl WritebatchIterator for Iter { type K = i32...
{ panic!("failed reading data") }
conditional_block
writebatch.rs
use utils::{tmpdir}; use leveldb::database::{Database}; use leveldb::options::{Options,ReadOptions,WriteOptions}; use leveldb::database::kv::{KV}; use leveldb::database::batch::{Batch,Writebatch,WritebatchIterator}; #[test] fn test_writebatch() { let mut opts = Options::new(); opts.create_if_missing = true; ...
let data = data.unwrap(); assert_eq!(data, vec!(2)); }, Err(_) => { panic!("failed reading data") } } let read_opts2 = ReadOptions::new(); let res2 = database.get(read_opts2, 1); match res2 { Ok(data) => { assert!(data.is_none()) }, Err(_) => { pa...
Ok(data) => { assert!(data.is_some());
random_line_split
misc_utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {assertDefined} from '../../util/assert'; import {global} from '../../util/global'; import {RElement} from '....
* property names or interpolation strings. If it is in fact used in a property * binding, DebugElement.properties will not return the correct value for that * binding. However, there should be no runtime effect for real applications. * * This character is typically rendered as a question mark inside of a diamond. ...
* We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter * because it is a very uncommon character that is unlikely to be part of a user's
random_line_split
misc_utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {assertDefined} from '../../util/assert'; import {global} from '../../util/global'; import {RElement} from '....
export const defaultScheduler = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame || // browser only setTimeout // everything else ).bind(global); /** * * @codeGenApi */ export function ɵɵresolveWindow(element: REl...
{ if (typeof value == 'function') return value.name || value; if (typeof value == 'string') return value; if (value == null) return ''; if (typeof value == 'object' && typeof value.type == 'function') return value.type.name || value.type; return '' + value; }
identifier_body
misc_utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {assertDefined} from '../../util/assert'; import {global} from '../../util/global'; import {RElement} from '....
ring): boolean { return str.indexOf(INTERPOLATION_DELIMITER) >= 0; } /** * Unwrap a value which might be behind a closure (for forward declaration reasons). */ export function maybeUnwrapFn<T>(value: T | (() => T)): T { if (value instanceof Function) { return value(); } else { return value; } }
tadataString(str: st
identifier_name
index.test.js
/* global describe, expect, it */ const fishNames = require('../src/index'); const allFish = fishNames.all; describe('fish names', function() { describe('all', function() { it('should return an object containing all 200 fish names', function() { expect(Object.keys(allFish).length).toEqual(200); }); ...
fish => fishNames.allMaleFish[fish] ); const allFemaleFish = Object.keys(fishNames.allFemaleFish).map( fish => fishNames.allFemaleFish[fish] ); it('should ONLY contain names of male fish', function() { expect(allMaleFish).not.toEqual(expect.arrayContaining(allFemaleFish)); }); ...
describe('male/female fish', function() { const allMaleFish = Object.keys(fishNames.allMaleFish).map(
random_line_split
htmlModules.js
页① * pageBshowMode: string, 页面底部-显示方式:未配置默认所有页面;'article' => 仅文章页①; 'custom' => 仅自定义页① * * windowLB: htmlString, 全局窗口左下角② * windowRB: htmlString, 全局窗口右下角② * } * * ①注:在.md文件front matter配置`article: false`的页面是自定义页,未配置的默认是文章页(首页除外)。 * ②注:windowLB 和 windowRB:1.展示区块最大宽高200px*400px。2.请给自定义元素定一个不超过200px*400px的宽高。...
// windowRB: // `<!-- 固定160*160px --> // <ins class="adsbygoogle" // style="display:inline-block;max-width:160px;max-height:160px" // data-ad-client="ca-pub-7828333725993554" // data-ad-slot="8377369
// (adsbygoogle = window.adsbygoogle || []).push({}); // </script>`,
random_line_split
graph.js
ma.minorFragmentProfile", "mi"); var timetable = $.map(t2, function (record, index) { var newrec = { "name" : record.ma.majorFragmentId + "-" + record.mi.minorFragmentId, "category" : record.ma.majorFragmentId, "start" : (record.mi...
nodeStack.push(currItem); } return g; } // graph a "planstring" into the d3 svg handle "svg" function buildplangraph (svg, planstring) { var padding = 20; var graph = parseplan(planstring); var renderer = new dagreD3.Renderer(); renderer.zoo...
g.addEdge(null, currItem[0], top[0]); if (currItemIndent != stackTopIndent) nodeStack.push(top); if (currItemIndent >= stackTopIndent)
random_line_split
graph.js
(table, fieldpath, dest) { var faccess = accessor(fieldpath); return $.map(table, function (record, index) { var newrec = $.extend({}, record); newrec[dest] = faccess(newrec); return newrec; }); } // creates a function that will traverse tree of obje...
extract
identifier_name
graph.js
index 1 //Compare top-of-stack indent with current iterItem indent while (stackTopIndent >= currItemIndent) { top = nodeStack.pop(); stackTopIndent = top[1].length; } //Found parent //Add edge if Implicit src exists ...
{ globalconfig.profile = profile; if (profile.fragmentProfile !== undefined) { globalconfig.majorcolorscale = d3.scale.category20() .domain([0, d3.max(profile.fragmentProfile, accessor("majorFragmentId"))]); } }
identifier_body
templates.py
CommandError(message) else: top_dir = os.path.abspath(path.expanduser(target)) if not os.path.exists(top_dir): raise CommandError("Destination directory '%s' does not " "exist, please create it first." % top_dir) extensions = t...
Make sure that the file is writeable. Useful if our source is read-only. """
random_line_split
templates.py
The directory to which the template should be copied. :param options: The additional variables passed to project or app templates """ requires_system_checks = False # The supported URL schemes url_schemes = ['http', 'https', 'ftp'] # Can't perform any active locale changes during this command, ...
if self.verbosity >= 2: self.stdout.write("Creating %s\n" % new_path) try: shutil.copymode(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( ...
shutil.copyfile(old_path, new_path)
conditional_block
templates.py
def add_arguments(self, parser): parser.add_argument('name', help='Name of the application or project.') parser.add_argument('directory', nargs='?', help='Optional destination directory') parser.add_argument('--template', help='The path or URL to load the template from.') parser.add_...
splitext
identifier_name
templates.py
: The directory to which the template should be copied. :param options: The additional variables passed to project or app templates """ requires_system_checks = False # The supported URL schemes url_schemes = ['http', 'https', 'ftp'] # Can't perform any active locale changes during this command,...
the_path, info = urlretrieve(url, path.join(tempdir, filename)) except IOError as e: raise CommandError("couldn't download URL %s to %s: %s" % (url, filename, e)) used_name = the_path.split('/')[-1] # Trying to get better name from respons...
""" Downloads the given URL and returns the file name. """ def cleanup_url(url): tmp = url.rstrip('/') filename = tmp.split('/')[-1] if url.endswith('/'): display_url = tmp + '/' else: display_url = url r...
identifier_body
__init__.py
from __future__ import unicode_literals from zipfile import ZipFile import decimal import datetime from xml.dom.minidom import parseString from . import ods_components from .formula import Formula # Basic compatibility setup for Python 2 and Python 3. try: long except NameError: long = int try: unicode ...
(self, cells): """ Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing. """ if self.default_sheet is None: self.default_sheet = self.new_sheet() self.defaul...
writerow
identifier_name
__init__.py
from __future__ import unicode_literals from zipfile import ZipFile import decimal import datetime from xml.dom.minidom import parseString from . import ods_components from .formula import Formula # Basic compatibility setup for Python 2 and Python 3. try: long except NameError: long = int try: unicode ...
def writerows(self, rows): """ Write rows into the default sheet of the spreadsheet. :param rows: A list of rows, rows are lists of cells - see writerow. :return: Nothing. """ for row in rows: self.writerow(row) def new_sheet(self, name=None, cols=N...
""" Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing. """ if self.default_sheet is None: self.default_sheet = self.new_sheet() self.default_sheet.writerow(cells)
identifier_body
__init__.py
from __future__ import unicode_literals from zipfile import ZipFile import decimal import datetime from xml.dom.minidom import parseString from . import ods_components from .formula import Formula # Basic compatibility setup for Python 2 and Python 3. try: long except NameError: long = int try: unicode ...
def writerows(self, rows): for row in rows: self.writerow(row) def writer(odsfile, *args, **kwargs): """ Returns an ODSWriter object. Python 3: Make sure that the file you pass is mode b: f = open("spreadsheet.ods", "wb") odswriter.writer(f) ... ...
self.table.appendChild(row)
random_line_split
__init__.py
from __future__ import unicode_literals from zipfile import ZipFile import decimal import datetime from xml.dom.minidom import parseString from . import ods_components from .formula import Formula # Basic compatibility setup for Python 2 and Python 3. try: long except NameError: long = int try: unicode ...
else: # String and unknown types become string cells cell.setAttribute("office:value-type", "string") text = unicode(cell_data) if text: p = self.dom.createElement("text:p") p.appendChild(self.dom.createTextNode(t...
pass # Empty element
conditional_block
test_pandas_utils.py
import pytest import pandas as pd from lcdblib.pandas import utils @pytest.fixture(scope='session') def sample_table(): metadata = { 'sample': ['one', 'two'], 'tissue': ['ovary', 'testis'] } return pd.DataFrame(metadata) def test_cartesian_df(sample_table):
def test_cartesian_sf(sample_table): sf2 = pd.Series([100, 200], name='num') result = utils.cartesian_product(sample_table, sf2) # Compare a slice sf = result.iloc[0, :].sort_index() sf.name = '' test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index() a...
df2 = pd.DataFrame({'num': [100, 200]}) result = utils.cartesian_product(sample_table, df2) # Compare a slice sf = result.iloc[0, :].sort_index() sf.name = '' test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index() assert sf.equals(test_sf) assert result....
identifier_body
test_pandas_utils.py
import pytest import pandas as pd from lcdblib.pandas import utils @pytest.fixture(scope='session') def sample_table(): metadata = { 'sample': ['one', 'two'], 'tissue': ['ovary', 'testis'] } return pd.DataFrame(metadata) def test_cartesian_df(sample_table): df2 = pd.DataFrame({'num...
(sample_table): sf2 = pd.Series([100, 200], name='num') result = utils.cartesian_product(sample_table, sf2) # Compare a slice sf = result.iloc[0, :].sort_index() sf.name = '' test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index() assert sf.equals(test_sf...
test_cartesian_sf
identifier_name
test_pandas_utils.py
import pytest import pandas as pd from lcdblib.pandas import utils @pytest.fixture(scope='session') def sample_table(): metadata = { 'sample': ['one', 'two'], 'tissue': ['ovary', 'testis'] } return pd.DataFrame(metadata) def test_cartesian_df(sample_table): df2 = pd.DataFrame({'num...
test_sf = pd.Series({'sample': 'one', 'tissue': 'ovary', 'num': 100}, name='').sort_index() assert sf.equals(test_sf) assert result.shape == (4, 3)
random_line_split
taxonomy.py
[3] # Create the Citation object. self.citation = Citation() self.citation.loadFromDB(pgcur, res[1]) # Get the rank ID and taxonomy ID of the root taxon concept. query = """SELECT tc.rank_id, tc.taxonomy_id FROM taxon_concepts tc, ranks r WHERE tc.tc_id=...
(TaxonomyBase): """ A special case of Taxonomy that represents the MOL backbone taxonomy. Provides methods to link other taxonomies to the backbone taxonomy. Does not provide a persist() method because the backbone taxonomy metadata are set when the database tables are created. """ def __i...
BackboneTaxonomy
identifier_name
taxonomy.py
[3] # Create the Citation object. self.citation = Citation() self.citation.loadFromDB(pgcur, res[1]) # Get the rank ID and taxonomy ID of the root taxon concept. query = """SELECT tc.rank_id, tc.taxonomy_id FROM taxon_concepts tc, ranks r WHERE tc.tc_id=...
ptvisitor = PrintTaxonVisitor(numtaxa, maxdepth) ptvisitor.visit(self.roottaxon) def printAll(self, numtaxa=-1, maxdepth=-1): """ Prints a text representation of this taxonomy, including the tree of taxa. If numtaxa > 0, only the first numtaxa taxa will be printed. If max...
print '(Only traversing taxa tree to a depth of ' + str(maxdepth) + '.)'
conditional_block
taxonomy.py
res[3] # Create the Citation object. self.citation = Citation() self.citation.loadFromDB(pgcur, res[1]) # Get the rank ID and taxonomy ID of the root taxon concept. query = """SELECT tc.rank_id, tc.taxonomy_id FROM taxon_concepts tc, ranks r WHERE tc.tc...
if numtaxa > 0: print '(Only printing first', numtaxa, 'taxa.)' if maxdepth > -1: print '(Only traversing taxa tree to a depth of ' + str(maxdepth) + '.)' ptvisitor = PrintTaxonVisitor(numtaxa, maxdepth) ptvisitor.visit(self.roottaxon) def printAll(self, num...
depth of maxdepth. """ print '** Taxa tree **'
random_line_split
taxonomy.py
[3] # Create the Citation object. self.citation = Citation() self.citation.loadFromDB(pgcur, res[1]) # Get the rank ID and taxonomy ID of the root taxon concept. query = """SELECT tc.rank_id, tc.taxonomy_id FROM taxon_concepts tc, ranks r WHERE tc.tc_id=...
class Taxonomy(TaxonomyBase): """ A class that represents a single taxonomy in the MOL taxonomy database. Provides methods to load a taxonomy from the database and persist a taxonomy to the database. Can also link a taxonomy to the backbone taxonomy. """ def __init__(self, taxonomy_id, name...
""" Prints a text representation of this taxonomy, including the tree of taxa. If numtaxa > 0, only the first numtaxa taxa will be printed. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. """ self.printTaxonomyInfo() print self.prin...
identifier_body
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
encoder: encoder, } } pub fn new(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) ...
encoding: encoding,
random_line_split
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
}
{ unsafe { let output = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = output.len() as u32; let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); ...
identifier_body
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding...
(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder...
new
identifier_name
main.js
require.config({ baseUrl: 'js', // urlArgs: '_=' + (new Date().getTime()), paths: { jquery: 'lib/jquery-1.11.1.min', underscore: 'lib/underscore-1.7.0.min', backbone: 'lib/backbone-1.1.2-min', marionette: 'lib/backbone.marionette.umd-2.2.0', handlebars: 'lib/hand...
'underscore', 'marionette', 'handlebars', 'app/app' ], function(_, Marionette, Handlebars, app) { 'use strict'; // Save app to window for debugging window.app = app; // setup our templates to use curly braces _.templateSettings = { evaluate : /\{\[([\s\S]+?)\]\}/g, ...
random_line_split
main.js
require.config({ baseUrl: 'js', // urlArgs: '_=' + (new Date().getTime()), paths: { jquery: 'lib/jquery-1.11.1.min', underscore: 'lib/underscore-1.7.0.min', backbone: 'lib/backbone-1.1.2-min', marionette: 'lib/backbone.marionette.umd-2.2.0', handlebars: 'lib/hand...
return template; }; // enables handlebars as our template library Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate) { return Handlebars.compile(rawTemplate); }; app.start(); });
{ var msg = 'Could not find template: "' + templateId + '"'; var err = new Error(msg); err.name = 'NoTemplateError'; throw err; }
conditional_block
search.js
class Search { constructor() { this.searchElement = document.querySelector('#search'); this.resultsContainer = document.querySelector('.results'); this.stationPreview = new StationPreview(); this.autoComplete = this.autoComplete.bind(this); this.onClick = this.onClick.bind(this); this.regist...
var stationPreview = this.stationPreview; this.getStopInfo(evt.target.id) .then(function(json) { stationPreview.renderStation(json); }) } getSearchResults(query) { query = query.trim(); return new Promise(function(resolve, reject) { if(query.length === 0) resolve([]); else...
onClick(evt) {
random_line_split
search.js
class Search { constructor() { this.searchElement = document.querySelector('#search'); this.resultsContainer = document.querySelector('.results'); this.stationPreview = new StationPreview(); this.autoComplete = this.autoComplete.bind(this); this.onClick = this.onClick.bind(this); this.regist...
(query) { query = query.trim(); return new Promise(function(resolve, reject) { if(query.length === 0) resolve([]); else fetch("https://api.tfl.gov.uk/Stoppoint/Search/" + query + "?modes=tube") .then(function(response) { response.json().then(function(json) { resolve(json.matc...
getSearchResults
identifier_name
search.js
class Search { constructor() { this.searchElement = document.querySelector('#search'); this.resultsContainer = document.querySelector('.results'); this.stationPreview = new StationPreview(); this.autoComplete = this.autoComplete.bind(this); this.onClick = this.onClick.bind(this); this.regist...
getSearchResults(query) { query = query.trim(); return new Promise(function(resolve, reject) { if(query.length === 0) resolve([]); else fetch("https://api.tfl.gov.uk/Stoppoint/Search/" + query + "?modes=tube") .then(function(response) { response.json().then(function(json) { ...
{ var stationPreview = this.stationPreview; this.getStopInfo(evt.target.id) .then(function(json) { stationPreview.renderStation(json); }) }
identifier_body
snake_agent.py
# Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem. import random from action import Action # nie zmieniac nazwy klasy class Agent: # nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku def __init__(self, p, pj, pn, height, width, areaMap): ...
# dopisac reszte inicjalizacji agenta return # nie zmieniac naglowka metody, tutaj agent dokonuje obserwacji swiata # sensor przyjmuje wartosc True gdy agent ma uczucie stania w jamie def sense(self, sensor): pass # nie zmieniac naglowka metody, tutaj agent decyduje w ktora s...
self.hist.append([]) for x in range(self.width): self.hist[y].append(float(y + x) / (self.width + self.height - 2))
conditional_block
snake_agent.py
# Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem. import random from action import Action # nie zmieniac nazwy klasy class Agent: # nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku def __init__(self, p, pj, pn, height, width, areaMap): ...
# nie zmieniac naglowka metody, tutaj agent dokonuje obserwacji swiata # sensor przyjmuje wartosc True gdy agent ma uczucie stania w jamie def sense(self, sensor): pass # nie zmieniac naglowka metody, tutaj agent decyduje w ktora strone sie ruszyc, # funkcja MUSI zwrocic jedna z wartosci ...
self.times_moved = 0 self.direction = Action.LEFT # w ten sposob mozna zapamietac zmienne obiektu self.p = p self.pj = pj self.pn = pn self.height = height self.width = width self.map = areaMap # w tym przykladzie histogram wypelniany jest tak ab...
identifier_body
snake_agent.py
# Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem. import random from action import Action # nie zmieniac nazwy klasy class Agent: # nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku def __init__(self, p, pj, pn, height, width, areaMap): ...
(self, sensor): pass # nie zmieniac naglowka metody, tutaj agent decyduje w ktora strone sie ruszyc, # funkcja MUSI zwrocic jedna z wartosci [Action.UP, Action.DOWN, Action.LEFT, Action.RIGHT] def move(self): if self.times_moved < self.width - 1: self.times_moved += 1 ...
sense
identifier_name
snake_agent.py
# Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem. import random from action import Action # nie zmieniac nazwy klasy class Agent: # nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku def __init__(self, p, pj, pn, height, width, areaMap): ...
# w ten sposob mozna zapamietac zmienne obiektu self.p = p self.pj = pj self.pn = pn self.height = height self.width = width self.map = areaMap # w tym przykladzie histogram wypelniany jest tak aby na planszy wyszedl gradient self.hist = [] ...
self.direction = Action.LEFT
random_line_split
ios-device-product-name-mapper.ts
import { IStringDictionary } from "../../declarations"; import { injector } from "../../yok"; class IosDeviceProductNameMapper implements Mobile.IiOSDeviceProductNameMapper { // http://support.hockeyapp.net/kb/client-integration-ios-mac-os-x/ios-device-types private map: IStringDictionary = { "iPhone1,1": "iPhone"...
} injector.register("iOSDeviceProductNameMapper", IosDeviceProductNameMapper);
{ return this.map[deviceType]; }
identifier_body
ios-device-product-name-mapper.ts
import { IStringDictionary } from "../../declarations"; import { injector } from "../../yok"; class
implements Mobile.IiOSDeviceProductNameMapper { // http://support.hockeyapp.net/kb/client-integration-ios-mac-os-x/ios-device-types private map: IStringDictionary = { "iPhone1,1": "iPhone", "iPhone1,2": "iPhone 3G", "iPhone2,1": "iPhone 3GS", "iPhone3,1": "iPhone 4 (GSM)", "iPhone3,3": "iPhone 4 (CDMA)", ...
IosDeviceProductNameMapper
identifier_name
ios-device-product-name-mapper.ts
import { IStringDictionary } from "../../declarations"; import { injector } from "../../yok"; class IosDeviceProductNameMapper implements Mobile.IiOSDeviceProductNameMapper { // http://support.hockeyapp.net/kb/client-integration-ios-mac-os-x/ios-device-types private map: IStringDictionary = { "iPhone1,1": "iPhone"...
"iPad2,4": "iPad 2 (Wi-Fi, revised)", "iPad2,5": "iPad mini (Wi-Fi)", "iPad2,6": "iPad mini (A1454)", "iPad2,7": "iPad mini (A1455)", "iPad3,1": "iPad (3rd gen, Wi-Fi)", "iPad3,2": "iPad (3rd gen, Wi-Fi+LTE Verizon)", "iPad3,3": "iPad (3rd gen, Wi-Fi+LTE AT&T)", "iPad3,4": "iPad (4th gen, Wi-Fi)", "iP...
"iPad2,2": "iPad 2 (GSM)", "iPad2,3": "iPad 2 (CDMA)",
random_line_split
models.py
invenio.utils.text import slugify from sqlalchemy.dialects import mysql from sqlalchemy.event import listens_for from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.schema import Index class KnwKB(db.Model): """Represent a KnwKB record.""" KNWKB_TYPES = { 'written_as...
self._kbtype = kbtype def is_dynamic(self): """Return true if the type is dynamic.""" return self._kbtype == 'd' def to_dict(self): """Return a dict representation of KnwKB.""" mydict = {'id': self.id, 'name': self.name, 'description': self.descriptio...
raise ValueError('unknown type "{value}", please use one of \ following values: "taxonomy", "dynamic" or \ "written_as"'.format(value=value))
conditional_block
models.py
from invenio.utils.text import slugify from sqlalchemy.dialects import mysql from sqlalchemy.event import listens_for from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.schema import Index class KnwKB(db.Model): """Represent a KnwKB record.""" KNWKB_TYPES = { 'writte...
if searchtype == 's' and searchvalue: searchvalue = '%' + searchvalue + '%' if searchtype == 'sw' and searchvalue: # startswith searchvalue = searchvalue + '%' if not searchvalue: searchvalue = '%' # execute query return db.session.execute( ...
"E.g. [(kval.m_value,) for kval in " "KnwKBRVAL.query_kb_mappings(kb_id).all()]") # prepare filters if searchtype == 's': searchkey = '%' + searchkey + '%'
random_line_split
models.py
invenio.utils.text import slugify from sqlalchemy.dialects import mysql from sqlalchemy.event import listens_for from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.schema import Index class KnwKB(db.Model): """Represent a KnwKB record.""" KNWKB_TYPES = { 'written_as...
@listens_for(KnwKB, 'after_delete') def del_kwnkb(mapper, connection, target): """Remove taxonomy file.""" if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']): # Delete taxonomy file if os.path.isfile(target.get_filename()): os.remove(target.get_filename()) class KnwKBDDEF(db.Mod...
"""Construct the file name for taxonomy knoledge.""" return cfg['CFG_WEBDIR'] + "/kbfiles/" \ + str(self.id) + ".rdf"
identifier_body
models.py
invenio.utils.text import slugify from sqlalchemy.dialects import mysql from sqlalchemy.event import listens_for from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.schema import Index class KnwKB(db.Model): """Represent a KnwKB record.""" KNWKB_TYPES = { 'written_as...
(self): """Construct the file name for taxonomy knoledge.""" return cfg['CFG_WEBDIR'] + "/kbfiles/" \ + str(self.id) + ".rdf" @listens_for(KnwKB, 'after_delete') def del_kwnkb(mapper, connection, target): """Remove taxonomy file.""" if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']...
get_filename
identifier_name
test_urllibnet.py
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import mimetools class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttim...
def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus # address. self.assertRaises(IOError, urllib.urlopen, "http://www.sadflkjsasadf.com/") class urlretrieveNetworkTests(unittest.TestCase): """Tests urllib.urlretrieve ...
if (sys.platform in ('win32',) or not hasattr(os, 'fdopen')): # On Windows, socket handles are not file descriptors; this # test can't pass on Windows. return # Make sure fd returned by fileno is valid. open_url = urllib.urlopen("http://www.python.org/...
identifier_body
test_urllibnet.py
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import mimetools class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttim...
# address. self.assertRaises(IOError, urllib.urlopen, "http://www.sadflkjsasadf.com/") class urlretrieveNetworkTests(unittest.TestCase): """Tests urllib.urlretrieve using the network.""" def test_basic(self): # Test basic functionality. file_location,i...
FILE.close() def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus
random_line_split
test_urllibnet.py
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import mimetools class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttim...
(unittest.TestCase): """Tests urllib.urlopen using the network. These tests are not exhaustive. Assuming that testing using files does a good job overall of some of the basic interface features. There are no tests exercising the optional 'data' and 'proxies' arguments. No tests for transparent r...
urlopenNetworkTests
identifier_name
test_urllibnet.py
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import mimetools class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttim...
test_main()
conditional_block
mir_overflow_off.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
main
identifier_name
mir_overflow_off.rs
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // c...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
mir_overflow_off.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
/// Returns a short string to announce Rust support during startup. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub extern "C" fn rust_welcome_string() -> RustString { let s = CStri...
{ let res = str.as_ptr(); forget(str); res }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
(_str: RustString) { // Empty body: Just drop _str and we're done (Drop takes care of it). } /// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mang...
rust_str_free
identifier_name
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples ...
/// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char { let res = ...
}
random_line_split
PageLoad.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import type {NetworkRequest} from './NetworkRequest.js'; export class PageLoad { id: number; url: string; startTime: number; loadTime!: number; ...
private static lastIdentifier = 0; } const pageLoadForRequest = new WeakMap<NetworkRequest, PageLoad>();
{ pageLoadForRequest.set(request, this); }
identifier_body
PageLoad.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import type {NetworkRequest} from './NetworkRequest.js'; export class PageLoad { id: number; url: string; startTime: number; loadTime!: number; ...
(mainRequest: NetworkRequest) { this.id = ++PageLoad.lastIdentifier; this.url = mainRequest.url(); this.startTime = mainRequest.startTime; this.mainRequest = mainRequest; } static forRequest(request: NetworkRequest): PageLoad|null { return pageLoadForRequest.get(request) || null; } bindReq...
constructor
identifier_name
PageLoad.ts
// found in the LICENSE file. import type {NetworkRequest} from './NetworkRequest.js'; export class PageLoad { id: number; url: string; startTime: number; loadTime!: number; contentLoadTime!: number; mainRequest: NetworkRequest; constructor(mainRequest: NetworkRequest) { this.id = ++PageLoad.lastId...
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be
random_line_split
serializers.py
from rest_framework import serializers as ser from rest_framework import exceptions from framework.auth.oauth_scopes import public_scopes from website.models import ApiOAuth2PersonalToken from api.base.serializers import JSONAPISerializer, LinksField, IDField, TypeField class ApiOAuth2PersonalTokenSerializer(JSONAP...
(validated_data): scopes_set = set(validated_data['scopes'].split(' ')) for scope in scopes_set: if scope not in public_scopes or not public_scopes[scope].is_public: raise exceptions.ValidationError('User requested invalid scope')
validate_requested_scopes
identifier_name
serializers.py
from rest_framework import serializers as ser from rest_framework import exceptions from framework.auth.oauth_scopes import public_scopes from website.models import ApiOAuth2PersonalToken from api.base.serializers import JSONAPISerializer, LinksField, IDField, TypeField class ApiOAuth2PersonalTokenSerializer(JSONAP...
return data def create(self, validated_data): validate_requested_scopes(validated_data) instance = ApiOAuth2PersonalToken(**validated_data) instance.save() return instance def update(self, instance, validated_data): validate_requested_scopes(validated_data) ...
data['attributes'].pop('token_id')
conditional_block
serializers.py
from rest_framework import serializers as ser from rest_framework import exceptions from framework.auth.oauth_scopes import public_scopes from website.models import ApiOAuth2PersonalToken from api.base.serializers import JSONAPISerializer, LinksField, IDField, TypeField class ApiOAuth2PersonalTokenSerializer(JSONAP...
links = LinksField({ 'html': 'absolute_url' }) def absolute_url(self, obj): return obj.absolute_url def to_representation(self, obj, envelope='data'): data = super(ApiOAuth2PersonalTokenSerializer, self).to_representation(obj, envelope=envelope) # Make sure users only s...
"""Serialize data about a registered personal access token""" id = IDField(source='_id', read_only=True, help_text='The object ID for this token (automatically generated)') type = TypeField() name = ser.CharField(help_text='A short, descriptive name for this token', required=True)...
identifier_body
serializers.py
from rest_framework import serializers as ser from rest_framework import exceptions from framework.auth.oauth_scopes import public_scopes from website.models import ApiOAuth2PersonalToken from api.base.serializers import JSONAPISerializer, LinksField, IDField, TypeField class ApiOAuth2PersonalTokenSerializer(JSONAP...
scopes = ser.CharField(help_text='Governs permissions associated with this token', required=True) token_id = ser.CharField(read_only=True, allow_blank=True) class Meta: type_ = 'tokens' links = LinksField({ 'html': 'absolute_url' }) def absolute_url...
owner = ser.CharField(help_text='The user who owns this token', read_only=True, # Don't let user register a token in someone else's name source='owner._id')
random_line_split
circle.js
/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. Copyright 2015-2016 Teeming Society. 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 a...
var view = this.view this.mesh = this.vertexstruct.array(); GLGeom.createCircle(view.radius, view.detail, function(triidx,v1,v2,v3,n1,n2,n3,t1,t2,t3,faceidx){ this.mesh.push(v1,n1,t1); this.mesh.push(v2,n2,t2); this.mesh.push(v3,n3,t3); }.bind(this)) } } })
} this.shape3d = { update:function(){
random_line_split
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
} impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DocumentAttributes { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let body = value.1; Ok(serde_json::from_slice(body)?) } } impl<'a> std::convert::From<&'a DocumentAttributes> for IfMa...
{ self.attachments = value.into(); }
identifier_body
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
(&mut self, value: u64) { self.ts = value; } pub fn set_self<T>(&mut self, value: T) where T: Into<String>, { self._self = value.into(); } pub fn set_etag<T>(&mut self, value: T) where T: Into<String>, { self.etag = value.into(); } pub f...
set_ts
identifier_name
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(re...
attachments: "attachments".to_owned(), }; a.set_attachments("new_attachments".to_owned()); } }
etag: "etag".to_owned(),
random_line_split
utf8.ts
// 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...
/** @ignore */ export const decodeUtf8 = ((TextDecoder) => { if (useNativeEncoders || !_Buffer) { const decoder = new TextDecoder(); return decoder.decode.bind(decoder); } return (input: ArrayBufferLike | ArrayBufferView) => { const { buffer, byteOffset, length } = toUint8Array(inpu...
const useNativeEncoders = typeof TextDecoder === 'function' && typeof TextEncoder === 'function';
random_line_split